Cryptographic Token Interface Standard

PKCS#11


Functions

Cryptoki's functions are organized into the following categories:

A Cryptoki library need not support every function in the Cryptoki API. However, even an unsupported function should have a "stub" in the library which simply returns the value CKR_FUNCTION_NOT_SUPPORTED. If a Cryptoki API function is unsupported, its pointer in the library's CK_FUNCTION_LIST structure (as obtained by C_GetFunctionList) should be NULL_PTR (see Section).

Function return values

Universal Cryptoki function return values

Any Cryptoki function can return any of the following values:

Because the above values can be returned by any Cryptoki function, they will never explicitly be mentioned as possible returns when the Cryptoki functions are described. All other return values are more specific to particular functions, and will be listed with all relevant functions.

Cryptoki function return values for functions that use a session handle

Any Cryptoki function that takes a session handle as one of its arguments (i.e., any Cryptoki function except for C_Initialize, C_Finalize, C_GetInfo, C_GetFunctionList, C_GetSlotList, C_GetSlotInfo, C_GetTokenInfo, C_GetMechanismList, C_GetMechanismInfo, C_InitToken, C_OpenSession, and C_CloseAllSessions) can return the following values:

In practice, it is often not crucial (or possible) for a Cryptoki library to be able to make a distinction between a token being removed before a function invokation and a token being removed during a function execution.

Cryptoki function return values for functions that use a token

Any Cryptoki function that uses a token (i.e., any Cryptoki function except for C_Initialize, C_Finalize, C_GetInfo, C_GetFunctionList, C_GetSlotList, or C_GetSlotInfo) can return any of the following values:

In practice, it is often not crucial (or possible) for a Cryptoki library to be able to make a distinction between a token being removed before a function invokation and a token being removed during a function execution.

All the other Cryptoki function return values

The other Cryptoki function returns follow. Except as mentioned in the descriptions of particular error codes, there are in general no particular priorities among the errors listed below, i.e., if more than one error code might apply to a function's execution, the function may return any applicable error code.

In general, error codes from Section take precedence over error codes from Section , which take precedence over error codes from Section , which take precedence over error codes from Section . One minor implication of this is that functions that use a session handle never return the error code CKR_TOKEN_NOT_PRESENT (they return CKR_SESSION_HANDLE_INVALID instead). Other than these precedences, if more than one error code might apply to a Cryptoki call, any of the applicable error codes may be returned. Exceptions to this rule will be explicitly mentioned.

Conventions for functions which return output in a variable-length buffer

A number of the functions defined in Cryptoki return output produced by some cryptographic mechanism. The amount of output returned by these functions is returned in a variable-length application-supplied buffer. An example of a function of this sort is C_Encrypt, which takes some plaintext as an argument, and outputs a buffer full of ciphertext.

These functions have some common calling conventions, which we describe here. Two of the arguments to the function are a pointer to the output buffer (say pBuf) and a pointer to a location which will hold the length of the output produced (say pulBufLen). There are two ways for an application to call such a function:

  1. If pBuf is NULL_PTR, then all that the function does is return (in *pulBufLen) a number of bytes which would suffice to hold the cryptographic output produced from the input to the function. This number may somewhat exceed the precise number of bytes needed, but should not exceed it by a large amount. CKR_OK is returned by the function.

  2. If pBuf is not NULL_PTR, then *pulBufLen must contain the size in bytes of the buffer pointed to by pBuf. If that buffer is large enough to hold the cryptographic output produced from the input to the function, then that cryptographic output is placed there, and CKR_OK is returned by the function. If the buffer is not large enough, then CKR_BUFFER_TOO_SMALL is returned. In either case, *pulBufLen is set to hold the exact number of bytes needed to hold the cryptographic output produced from the input to the function.

All functions which use the above convention will explicitly say so.

Cryptographic functions which return output in a variable-length buffer should always return as much output as can be computed from what has been passed in to them thus far. As an example, consider a session which is performing a multiple-part decryption operation with DES in cipher-block chaining mode with PKCS padding. Suppose that, initially, 8 bytes of ciphertext are passed to the C_DecryptUpdate function. The blocksize of DES is 8 bytes, but the PKCS padding makes it unclear at this stage whether the ciphertext was produced from encrypting a 0-byte string, or from encrypting some string of length at least 8 bytes. Hence the call to C_DecryptUpdate should return 0 bytes of plaintext. If a single additional byte of ciphertext is subsequently supplied by C_DecryptUpdate, the call to C_DecryptUpdate should return 8 bytes of plaintext (one full DES block).

Disclaimer concerning sample code

For the remainder of Section , we enumerate the various functions defined in Cryptoki. Most functions will be shown in use in at least one sample code snippet. For the sake of brevity, sample code will frequently be somewhat incomplete. In particular, sample code will generally ignore possible error returns from C library functions, and also will not deal with Cryptoki error returns in a realistic fashion.

General-purpose functions

Cryptoki provides the following general-purpose functions. These functions do not run in parallel with the application.

C_Initialize

CK_RV C_Initialize(
CK_VOID_PTR pReserved
);

C_Initialize initializes the Cryptoki library. C_Initialize should be the first Cryptoki call made by an application, except for calls to C_GetFunctionList. What this function actually does is implementation-dependent: for example, it may cause Cryptoki to initialize its internal memory buffers, or any other resources it requires; or it may perform no action.

Parameters:
pReserved is reserved for future versions: for this version, it should be set to NULL_PTR.
If several applications are using Cryptoki, each one should call C_Initialize. Every call to C_Initialize should (eventually) be succeeded by a single call to C_Finalize.

Returns:
none other than the "universal" return values.
See also:
C_GetInfo.

C_Finalize

CK_RV C_Finalize(
CK_VOID_PTR pReserved
);

C_Finalize is called to indicate that an application is finished with the Cryptoki library. It should be the last Cryptoki call made by an application.

Parameters:
pReserved is reserved for future versions: for this version, it should be set to NULL_PTR.
If several applications are using Cryptoki, each one should call C_Finalize. Every call to C_Finalize should be preceded by a single call to C_Initialize ; in between the two calls, an application makes calls to other Cryptoki functions.

Returns:
none other than the "universal" return values.
See also:
C_GetInfo.

C_GetInfo

CK_RV C_GetInfo(
CK_INFO_PTR pInfo
);

C_GetInfo returns general information about Cryptoki.

Parameters:
pInfo points to the location that receives the information.
Returns:
none other than the "universal" return values.
Example:

CK_INFO info;
CK_RV rv;
rv = C_Initialize(NULL_PTR);
assert(rv == CKR_OK);
rv = C_GetInfo(&info);
assert(rv == CKR_OK);
if(info.version.major == 2) {
/* Do lots of interesting cryptographic things with the token */
.
.
.
}
rv = C_Finalize(NULL_PTR);
assert(rv == CKR_OK);

C_GetFunctionList

CK_RV C_GetFunctionList(
CK_FUNCTION_LIST_PTR_PTR ppFunctionList
);

C_GetFunctionList obtains a pointer to the Cryptoki library's list of function pointers.

Parameters:
ppFunctionList points to a value which will receive a pointer to the library's CK_FUNCTION_LIST structure, which contains function pointers for all the Cryptoki API routines in the library. The pointer obtained may point into memory which is owned by the Cryptoki library, and which may or may not be writable. In any case, no attempt should be made to write to this memory.
C_GetFunctionList is the only Cryptoki function which an application may call before calling C_Initialize. It is provided to make it easier and faster for applications to use shared Cryptoki libraries and to use more than one Cryptoki library simultaneously.

Returns:
none other than the "universal" return values.
Example:

CK_FUNCTION_LIST_PTR pFunctionList;
CK_C_Initialize pC_Initialize;
CK_RV rv;
/* It's OK to call C_GetFunctionList before calling C_Initialize */
rv = C_GetFunctionList(&pFunctionList);
assert(rv == CKR_OK);
pC_Initialize = pFunctionList -> C_Initialize;
/* Call the C_Initialize function in the library */
rv = (*pC_Initialize)(NULL_PTR);

Slot and token management functions

Cryptoki provides the following functions for slot and token management. These functions do not run in parallel with the application.

C_GetSlotList

CK_RV C_GetSlotList(
CK_BBOOL tokenPresent,
CK_SLOT_ID_PTR pSlotList,
CK_ULONG_PTR pulCount
);

C_GetSlotList is used to obtain a list of slots in the system.

Parameters:
tokenPresent indicates whether the list obtained includes only those slots with a token present (TRUE), or all slots (FALSE);
pulCount points to the location that receives the number of slots.
There are two ways for an application to call C_GetSlotList :

  1. If pSlotList is NULL_PTR, then all that C_GetSlotList does is return (in *pulCount) the number of slots, without actually returning a list of slots. The contents of the buffer pointed to by pulCount on entry to C_GetSlotList has no meaning in this case, and the call returns the value CKR_OK.

  2. If pSlotList is not NULL_PTR, then *pulCount must contain the size (in terms of CK_SLOT_ID elements) of the buffer pointed to by pSlotList. If that buffer is large enough to hold the list of slots, then the list is returned in it, and CKR_OK is returned. If not, then the call to C_GetSlotList returns the value CKR_BUFFER_TOO_SMALL. In either case, the value *pulCount is set to hold the number of slots.

Because C_GetSlotList does not allocate any space of its own, an application will often call C_GetSlotList twice (or sometimes even more times"if an application is trying to get a list of all slots with a token present, then the number of such slots can change between when the application asks for how many such slots there are, and when the application asks for the slots themselves). However, this is by no means required.

Returns:
CKR_BUFFER_TOO_SMALL.
Example:

CK_ULONG ulSlotCount, ulSlotWithTokenCount;
CK_SLOT_ID_PTR pSlotList, pSlotWithTokenList;
CK_RV rv;
/* Get list of all slots */
rv = C_GetSlotList(FALSE, NULL_PTR, &ulSlotCount);
if (rv == CKR_OK) {
pSlotList =
(CK_SLOT_ID_PTR) malloc(ulSlotCount*sizeof(CK_SLOT_ID));
rv = C_GetSlotList(FALSE, pSlotList, &ulSlotCount);
if (rv == CKR_OK) {
/* Now use that list of all slots */
.
.
.
}
free(pSlotList);
}
/* Get list of all slots with a token present */
pSlotWithTokenList = (CK_SLOT_ID_PTR) malloc(0);
ulSlotWithTokenCount = 0;
while (1) {
rv = C_GetSlotList(
TRUE, pSlotWithTokenList, ulSlotWithTokenCount);
if (rv != CKR_BUFFER_TOO_SMALL)
break;
pSlotWithTokenList = realloc(
pSlotWithTokenList,
ulSlotWithTokenList*sizeof(CK_SLOT_ID));
}
if (rv == CKR_OK) {
/* Now use that list of all slots with a token present */
.
.
.
}
free(pSlotWithTokenList);

C_GetSlotInfo

CK_RV C_GetSlotInfo(
CK_SLOT_ID slotID,
CK_SLOT_INFO_PTR pInfo
);

C_GetSlotInfo obtains information about a particular slot in the system.

Parameters:
slotID is the ID of the slot;
pInfo points to the location that receives the slot information.
Returns:
CKR_DEVICE_ERROR, CKR_SLOT_ID_INVALID.
See also:
C_GetTokenInfo.'''

C_GetTokenInfo

CK_RV C_GetTokenInfo(
CK_SLOT_ID slotID,
CK_TOKEN_INFO_PTR pInfo
);

C_GetTokenInfo obtains information about a particular token in the system.

Parameters:
slotID is the ID of the token's slot;
pInfo points to the location that receives the token information.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED.
Example:

CK_ULONG ulCount;
CK_SLOT_ID_PTR pSlotList;
CK_SLOT_INFO slotInfo;
CK_TOKEN_INFO tokenInfo;
CK_RV rv;
rv = C_GetSlotList(FALSE, NULL_PTR, &ulCount);
if ((rv == CKR_OK) && (ulCount > 0)) {
pSlotList = (CK_SLOT_ID_PTR) malloc(ulCount*sizeof(CK_SLOT_ID));
rv = C_GetSlotList(FALSE, pSlotList, &ulCount);
assert(rv == CKR_OK);
/* Get slot information for first slot */
rv = C_GetSlotInfo(pSlotList[0], &slotInfo);
assert(rv == CKR_OK);
/* Get token information for first slot */
rv = C_GetTokenInfo(pSlotList[0], &tokenInfo);
if (rv == CKR_TOKEN_NOT_PRESENT) {
.
.
.
}
.
.
.
free(pSlotList);
}

C_GetMechanismList

CK_RV C_GetMechanismList(
CK_SLOT_ID slotID,
CK_MECHANISM_TYPE_PTR pMechanismList,
CK_ULONG_PTR pulCount
);

C_GetMechanismList is used to obtain a list of mechanism types supported by a token.

Parameters:
SlotID is the ID of the token's slot;
pulCount points to the location that receives the number of mechanisms.
There are two ways for an application to call C_GetMechanismList :

  1. If pMechanismList is NULL_PTR, then all that C_GetMechanismList does is return (in *pulCount) the number of mechanisms, without actually returning a list of mechanisms. The contents of *pulCount on entry to C_GetMechanismList has no meaning in this case, and the call returns the value CKR_OK.

  2. If pMechanismList is not NULL_PTR, then *pulCount must contain the size (in terms of CK_MECHANISM_TYPE elements) of the buffer pointed to by pMechanismList. If that buffer is large enough to hold the list of mechanisms, then the list is returned in it, and CKR_OK is returned. If not, then the call to C_GetMechanismList returns the value CKR_BUFFER_TOO_SMALL. In either case, the value *pulCount is set to hold the number of mechanisms.

Because C_GetMechanismList does not allocate any space of its own, an application will often call C_GetMechanismList twice. However, this is by no means required.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED.
Example:

CK_SLOT_ID slotID;
CK_ULONG ulCount;
CK_MECHANISM_TYPE_PTR pMechanismList;
CK_RV rv;
.
.
.
rv = C_GetMechanismList(slotID, NULL_PTR, &ulCount);
if ((rv == CKR_OK) && (ulCount > 0)) {
pMechanismList =
(CK_MECHANISM_TYPE_PTR)
malloc(ulCount*sizeof(CK_MECHANISM_TYPE));
rv = C_GetMechanismList(slotID, pMechanismList, &ulCount);
if (rv == CKR_OK) {
.
.
.
}
free(pMechanismList);
}

C_GetMechanismInfo

CK_RV C_GetMechanismInfo(
CK_SLOT_ID slotID,
CK_MECHANISM_TYPE type,
CK_MECHANISM_INFO_PTR pInfo
);

C_GetMechanismInfo obtains information about a particular mechanism possibly supported by a token.

Parameters:
slotID is the ID of the token's slot;
type is the type of mechanism;
pInfo points to the location that receives the mechanism information.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_MECHANISM_INVALID, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED.
Example:

CK_SLOT_ID slotID;
CK_MECHANISM_INFO info;
CK_RV rv;
.
.
.
/* Get information about the CKM_MD2 mechanism for this token */
rv = C_GetMechanismInfo(slotID, CKM_MD2, &info);
if (rv == CKR_OK) {
if (info.flags & CKF_DIGEST) {
.
.
.
}
}

C_InitToken

CK_RV C_InitToken(
CK_SLOT_ID slotID,
CK_CHAR_PTR pPin,
CK_ULONG ulPinLen,
CK_CHAR_PTR pLabel
);

C_InitToken initializes a token.

Parameters:
slotID is the ID of the token's slot;
pPin points to the SO's initial PIN;
ulPinLen is the length in bytes of the PIN;
pLabel points to the 32-byte label of the token (must be padded with blank characters).
When a token is initialized, all objects that can be destroyed are destroyed (i.e., all except for "indestructible" objects such as keys built into the token). Also, access by the normal user is disabled until the SO sets the normal user's PIN. Depending on the token, some "default" objects may be created, and attributes of some objects may be set to default values.

If the token has a "protected authentication path", as indicated by the CKR_PROTECTED_AUTHENTICATION_PATH flag in its CK_TOKEN_INFO being set, then that means that there is some way for a user to be authenticated to the token without having the application send a PIN through the Cryptoki library. One such possibility is that the user enters a PIN on a PINpad on the token itself, or on the slot device. To initialize a token with such a protected authentication path, the pPin parameter to C_InitToken should be NULL_PTR. During the execution of C_InitToken, the SO's PIN will be entered through the protected authentication path.

If the token has a protected authentication path other than a PINpad, then it is token-dependent whether or not C_InitToken can be used to initialize the token.

A token cannot be initialized if Cryptoki detects that an application has an open session with it; when a call to C_InitToken is made under such circumstances, the call fails with error CKR_SESSION_EXISTS. It may happen that some other application does have an open session with the token, but Cryptoki cannot detect this, because it cannot detect anything about other applications using the token. If this is the case, then what happens as a result of the C_InitToken call is undefined.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_PIN_INCORRECT, CKR_SESSION_EXISTS, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_TOKEN_WRITE_PROTECTED.
Example:

CK_SLOT_ID slotID;
CK_CHAR pin[] = {"MyPIN"};
CK_CHAR label[32];
CK_RV rv;
.
.
.
memset(label, ' ', sizeof(label));
memcpy(label, "My first token", sizeof("My first token"));
rv = C_InitToken(slotID, pin, sizeof(pin), label);
if (rv == CKR_OK) {
.
.
.
}

C_InitPIN

CK_RV C_InitPIN(
CK_SESSION_HANDLE hSession,
CK_CHAR_PTR pPin,
CK_ULONG ulPinLen
);

C_InitPIN initializes the normal user's PIN.

Parameters:
hSession is the session's handle;
pPin points to the normal user's PIN; ulPinLen is the length in bytes of the PIN.
C_InitPIN can only be called in the "R/W SO Functions" state. An attempt to call it from a session in any other state fails with error CKR_USER_NOT_LOGGED_IN.

If the token has a "protected authentication path", as indicated by the CKR_PROTECTED_AUTHENTICATION_PATH flag in its CK_TOKEN_INFO being set, then that means that there is some way for a user to be authenticated to the token without having the application send a PIN through the Cryptoki library. One such possibility is that the user enters a PIN on a PINpad on the token itself, or on the slot device. To initialize the normal user's PIN on a token with such a protected authentication path, the pPin parameter to C_InitPIN should be NULL_PTR. During the execution of C_InitPIN, the SO will enter the new PIN through the protected authentication path.

If the token has a protected authentication path other than a PINpad, then it is token-dependent whether or not C_InitPIN can be used to initialize the normal user's token access.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_PIN_INVALID, CKR_PIN_LEN_RANGE, CKR_SESSION_CLOSED, CKR_SESSION_READ_ONLY, CKR_SESSION_HANDLE_INVALID, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_CHAR newPin[]= {"NewPIN"};
CK_RV rv;
rv = C_InitPIN(hSession, newPin, sizeof(newPin));
if (rv == CKR_OK) {
.
.
.
}

C_SetPIN

CK_RV C_SetPIN(
CK_SESSION_HANDLE hSession,
CK_CHAR_PTR pOldPin,
CK_ULONG ulOldLen,
CK_CHAR_PTR pNewPin,
CK_ULONG ulNewLen
);

C_SetPIN modifies the PIN of the user that is currently logged in.

Parameters:
hSession is the session's handle;
pOldPin points to the old PIN;
ulOldLen is the length in bytes of the old PIN; pNewPin points to the new PIN;
ulNewLen is the length in bytes of the new PIN.
C_SetPIN can only be called in the "R/W SO Functions" state or "R/W User Functions" state. An attempt to call it from a session in any other state fails with error CKR_SESSION_READ_ONLY.

If the token has a "protected authentication path", as indicated by the CKR_PROTECTED_AUTHENTICATION_PATH flag in its CK_TOKEN_INFO being set, then that means that there is some way for a user to be authenticated to the token without having the application send a PIN through the Cryptoki library. One such possibility is that the user enters a PIN on a PINpad on the token itself, or on the slot device. To modify the current user's PIN on a token with such a protected authentication path, the pOldPin and pNewPin parameters to C_SetPIN should be NULL_PTR. During the execution of C_SetPIN, the current user will enter the old PIN and the new PIN through the protected authentication path. It is not specified how the PINpad should be used to enter two PINs; this varies.

If the token has a protected authentication path other than a PINpad, then it is token-dependent whether or not C_SetPIN can be used to modify the current user's PIN.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_PIN_INCORRECT, CKR_PIN_INVALID, CKR_PIN_LEN_RANGE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TOKEN_WRITE_PROTECTED.
Example:

CK_SESSION_HANDLE hSession;
CK_CHAR oldPin[] = {"OldPIN"};
CK_CHAR newPin[] = {"NewPIN"};
CK_RV rv;
rv = C_SetPIN(
hSession, oldPin, sizeof(oldPin), newPin, sizeof(newPin));
if (rv == CKR_OK) {
.
.
.
}

Session management functions

Cryptoki provides the following functions for session management. These functions do not run in parallel with the application.

A typical application might perform the following series of steps to make use of a token:

  1. Select a token.

  2. Make one or more calls to C_OpenSession to obtain sessions with the token.

  3. Call C_Login to log the user into the token. Since all sessions an application has with a token have a shared login state, C_Login only needs to be called for one session.

  4. Perform cryptographic operations using the sessions with the token.

  5. Call C_CloseSession once for each session that the application has with the token.

An application should not normally call C_CloseAllSessions or C_Logout to close its sessions with a token. This is because these functions can affect the sessions "owned" by other applications (see the discussion in Section for more information). Therefore, an application should call these functions only under exceptional circumstances, unless the application somehow "knows" that no other applications have sessions open with the token.

An application may have concurrent sessions with more than one token. It is also possible for a token to have concurrent sessions with more than one application.

C_OpenSession

CK_RV C_OpenSession(
CK_SLOT_ID slotID,
CK_FLAGS flags,
CK_VOID_PTR pApplication,
CK_NOTIFY Notify,
CK_SESSION_HANDLE_PTR phSession
);

C_OpenSession has two distinct functions: it can set up an application callback so that an application will be notified when a token is inserted into a particular slot, or it can open a session between an application and a token in a particular slot.

Parameters:
slotID is the slot's ID;
flags indicates the type of session;
pApplication is an application-defined pointer to be passed to the notification callback; Notify is the address of the notification callback function (see Section); phSession points to the location that receives the handle for the new session.
To set up a token insertion callback (instead of actually opening a session), the CKF_INSERTION_CALLBACK bit in the flags parameter should be set. As a result of setting up this callback, when a token is inserted into the specified slot, the application-supplied callback Notify will be called with parameters (0, CKN_TOKEN_INSERTION, pApplication). If a token is already present when C_OpenSession is called, then Notify will be called immediately (conceivably even before C_OpenSession returns).

When C_OpenSession is called to set up a token insertion callback, the return code is either CKR_INSERTION_CALLBACK_NOT_SUPPORTED (if the token doesn't support insertion callbacks) or CKR_OK (if the token does support insertion callbacks).

When opening a session with C_OpenSession, the flags parameter consists of the logical OR of zero or more bit flags defined in the CK_SESSION_INFO data type. For example, if no bits are set in the flags parameter, then C_OpenSession attempts to open a shared, read-only session, with certain cryptographic functions being performed in parallel with the application. Any or all of the CKF_EXCLUSIVE_SESSION, CKF_RW_SESSION, and CKF_SERIAL_SESSION bits can be set in the flags parameter to modify the type of session requested.

If an exclusive session is requested (by setting the CKF_EXCLUSIVE_SESSION bit), but is not available (because there is already a session open), C_OpenSession returns CKR_SESSION_EXISTS. If a parallel session is requested (by not setting the CKR_SERIAL_SESSION bit), but is not supported on this token, then C_OpenSession returns CKR_PARALLEL_NOT_SUPPORTED. These two error returns have equal priorities.

In a parallel session, cryptographic functions may return control to the application before completing (the return value CKR_FUNCTION_PARALLEL indicates that this condition applies). The application may then call C_GetFunctionStatus to obtain an updated status of the function's execution, which will continue to be CKR_FUNCTION_PARALLEL until the function completes, and CKR_OK or some other return value when the function completes. Alternatively, the application can wait until Cryptoki sends notification that the function has completed through the Notify callback. The application may also call C_CancelFunction to cancel the function before it completes.

Note that even in a parallel session, there is no guarantee that a particular function will execute in parallel. Therefore, an application should always check cryptographic functions' return codes to see whether the function is running in parallel, or whether it ran in serial [and is already finished].

If an application calls another function (cryptographic or otherwise) before one that is executing in parallel in the same session completes, Cryptoki will wait until the one that is executing completes. Thus, an application can run only one function at any given time in a given session. To achieve parallel execution of multiple functions, the application should open additional sessions.

Cryptographic functions running in serial with the application may periodically surrender control to the application by calling Notify with a CKN_SURRENDER callback so that the application may perform other operations or cancel the function.

Non-cryptographic functions always run in serial with the application, and do not surrender control. A function in a parallel session will never surrender control back to the application via a CKN_SURRENDER application callback, even if that particular function is actually executing in serial with the application.

There may be a limit on the number of concurrent sessions with the token, which may depend on whether the session is "read-only" or "read/write". An attempt to open a session which does not succeed because there are too many existing sessions of some type should return CKR_SESSION_COUNT.

If the token is write-protected (as indicated in the CK_TOKEN_INFO structure), then only read-only sessions may be opened with it.

If the application calling C_OpenSession already has a R/W SO session open with the token, then any attempt to open a R/O session with the token fails with error code CKR_SESSION_READ_WRITE_SO_EXISTS (see Section).

The Notify callback function is used by Cryptoki to notify the application of certain events. If the application does not wish to support callbacks, it should pass a value of NULL_PTR as the Notify parameter. See Section for more information about application callbacks.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_INSERTION_CALLBACK_NOT_SUPPORTED, CKR_SESSION_COUNT, CKR_SESSION_EXISTS, CKR_SESSION_EXCLUSIVE_EXISTS, CKR_SESSION_PARALLEL_NOT_SUPPORTED, CKR_SESSION_READ_WRITE_SO_EXISTS, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_TOKEN_WRITE_PROTECTED.
See also:
C_CloseSession.

C_CloseSession

CK_RV C_CloseSession(
CK_SESSION_HANDLE hSession
);

C_CloseSession closes a session between an application and a token.

Parameters:
hSession is the session's handle.
When a session is closed, all session objects created by the session are destroyed automatically, even if the application has other sessions "using" the objects (see Sections - for more details). If a function is running in parallel with the session, it is canceled.

Depending on the token, when the last open session any application has with the token is closed, the token may be "ejected" from its reader (if this capability exists).

Despite the fact this C_CloseSession is supposed to close a session, the return value CKR_SESSION_CLOSED is an error return. It indicates the (probably somewhat unlikely) event that while this function call was executing, another call was made to C_CloseSession to close this particular session, and that call finished executing first. Such uses of sessions are a bad idea, and Cryptoki makes little promise of what will occur in general if an application indulges in this sort of behavior.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SLOT_ID slotID;
CK_BYTE application;
CK_NOTIFY MyNotify;
CK_SESSION_HANDLE hSession;
CK_RV rv;
.
.
.
application = 17;
MyNotify = &EncryptionSessionCallback;
rv = C_OpenSession(
slotID, CKF_RW_SESSION,(CK_VOID_PTR) &application, MyNotify,
&hSession);
if (rv == CKR_OK) {
.
.
.
C_CloseSession(hSession);
}

C_CloseAllSessions

CK_RV C_CloseAllSessions(
CK_SLOT_ID slotID
);

C_CloseAllSessions closes all sessions an application has with a token.

Parameters:
slotID specifies the token's slot.
Because an application may have access to sessions "owned" by another application (see Section), this function should only be called under special circumstances. In general, an application should close all its sessions one at a time with C_CloseSession, rather than calling C_CloseAllSessions.

Depending on the token, when the last open session any application has with the token is closed, the token may be "ejected" from its reader (if this capability exists).

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT.
Example:

CK_SLOT_ID slotID;
CK_RV rv;
.
.
.
rv = C_CloseAllSessions(slotID);

C_GetSessionInfo

CK_RV C_GetSessionInfo(
CK_SESSION_HANDLE hSession,
CK_SESSION_INFO_PTR pInfo
);

C_GetSessionInfo obtains information about a session.

Parameters:
hSession is the session's handle;
pInfo points to the location that receives the session information.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_SESSION_INFO info;
CK_RV rv;
.
.
.
rv = C_GetSessionInfo(hSession, &info);
if (rv == CKR_OK) {
if (info.state == CKS_RW_USER_FUNCTIONS) {
.
.
.
}
.
.
.
}

C_GetOperationState

CK_RV C_GetOperationState(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pOperationState,
CK_ULONG_PTR pulOperationStateLen
);

C_GetOperationState obtains the cryptographic operations state of a session, encoded as a string of bytes.

Parameters:
hSession is the session's handle;
pOperationState points to the location that receives the state;
pulOperationStateLen points to the location that receives the length in bytes of the state.
Although the saved state output by C_GetOperationState is not really produced by a "cryptographic mechanism", C_GetOperationState nonetheless uses the convention described in Section on producing output.

Precisely what the "cryptographic operations state" this function saves is varies from token to token; however, this state is what is provided as input to C_SetOperationState to restore the cryptographic activities of a session.

Consider a session which is performing a message digest operation using SHA-1 (i.e., the session is using the CKM_SHA_1 mechanism). Suppose that the message digest operation was initialized properly, and that precisely 80 bytes of data have been supplied so far as input to SHA-1. The application now wants to "save the state" of this digest operation, so that it can continue it later. In this particular case, since SHA-1 processes 512 bits (64 bytes) of input at a time, the cryptographic operations state of the session most likely consists of three distinct parts: the state of SHA-1's 160-bit internal chaining variable; the 16 bytes of unprocessed input data; and some administrative data indicating that this saved state comes from a session which was performing SHA-1 hashing. Taken together, these three pieces of information suffice to continue the current hashing operation at a later time.

Consider next a session which is performing an encryption operation with DES (a block cipher with a block size of 64 bits) in CBC (cipher-block chaining) mode (i.e., the session is using the CKM_RC2_CBC mechanism). Suppose that precisely 22 bytes of data (in addition to an IV for the CBC mode) have been supplied so far as input to DES, which means that the first two 8-byte blocks of ciphertext have already been produced and output. In this case, the cryptographic operations state of the session most likely consists of three or four distinct parts: the second 8-byte block of ciphertext (this will be used for cipher-block chaining to produce the next block of ciphertext); the 6 bytes of data still awaiting encryption; some administrative data indicating that this saved state comes from a session which was performing DES encryption in CBC mode; and possibly the DES key being used for encryption (see C_SetOperationState for more information on whether or not the key is present in the saved state).

If a session is performing two cryptographic operations simultaneously (see Section), then the cryptographic operations state of the session will contain all the necessary information to restore both operations.

A session which is in the middle of executing a Cryptoki function cannot have its cryptographic operations state saved. An attempt to do so returns the error CKR_FUNCTION_PARALLEL.

An attempt to save the cryptographic operations state of a session which does not currently have some active saveable cryptographic operation(s) (encryption, decryption, digesting, signing without message recovery, verification without message recovery, or some legal combination of two of these) should fail with the error CKR_OPERATION_NOT_INITIALIZED.

An attempt to save the cryptographic operations state of a session which is performing an appropriate cryptographic operation (or two), but which cannot be satisfied for any of various reasons (certain necessary state information and/or key information can't leave the token, for example) should fail with the error CKR_STATE_UNSAVEABLE.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_STATE_UNSAVEABLE.
See also:
C_SetOperationState.

C_SetOperationState

CK_RV C_SetOperationState(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pOperationState,
CK_ULONG ulOperationStateLen,
CK_OBJECT_HANDLE hEncryptionKey,
CK_OBJECT_HANDLE hAuthenticationKey
);

C_SetOperationState restores the cryptographic operations state of a session from a string of bytes obtained with C_GetOperationState.

Parameters:
hSession is the session's handle;
pOperationState points to the location holding the saved state;
ulOperationStateLen holds the length of the saved state;
hEncryptionKey holds a handle to the key which will be used for an ongoing encryption or decryption operation in the restored session (or 0 if no encryption or decryption key is needed, either because no such operation is ongoing in the stored session or because all the necessary key information is present in the saved state);
hAuthenticationKey holds a handle to the key which will be used for an ongoing signature, MACing, or verification operation in the restored session (or 0 if no such key is needed, either because no such operation is ongoing in the stored session or because all the necessary key information is present in the saved state).
The state need not have been obtained from the same session (the "source session") as it is being restored to (the "destination session"). However, the source session and destination session should have a common session state (e.g., CKS_RW_USER_FUNCTIONS), and should be with a common token. There is also no guarantee that cryptographic operations state may be carried across logins, or across different Cryptoki implementations.

If C_SetOperationState is supplied with alleged saved cryptographic operations state which it can determine is not valid saved state (or is cryptographic operations state from a session with a different session state, or is cryptographic operations state from a different token), it fails with the error CKR_SAVED_STATE_INVALID.

Saved state obtained from calls to C_GetOperationState may or may not contain information about keys in use for ongoing cryptographic operations. If a saved cryptographic operations state has an ongoing encryption or decryption operation, and the key in use for the operation is not saved in the state, then it must be supplied to C_SetOperationState in the hEncryptionKey argument. If it is not, then C_SetOperationState will fail and return the error CKR_KEY_NEEDED. If the key in use for the operation is saved in the state, then it can be supplied in the hEncryptionKey argument, but this is not required.

Similarly, if a saved cryptographic operations state has an ongoing signature, MACing, or verification operation, and the key in use for the operation is not saved in the state, then it must be supplied to C_SetOperationState in the hAuthenticationKey argument. If it is not, then C_SetOperationState will fail with the error CKR_KEY_NEEDED. If the key in use for the operation is saved in the state, then it can be supplied in the hAuthenticationKey argument, but this is not required.

If an irrelevant key is supplied to C_SetOperationState call (e.g., a nonzero key handle is submitted in the hEncryptionKey argument, but the saved cryptographic operations state supplied does not have an ongoing encryption or decryption operation, then C_SetOperationState fails with the error CKR_KEY_NOT_NEEDED.

If a key is supplied as an argument to C_SetOperationState, and C_SetOperationState can somehow detect that this key was not the key being used in the source session for the supplied cryptographic operations state (it may be able to detect this if the key or a hash of the key is present in the saved state, for example), then C_SetOperationState fails with the error CKR_KEY_CHANGED.

An application can look at the CKF_RESTORE_KEY_NOT_NEEDED flag in the flags field of the CK_TOKEN_INFO field for a token to determine whether or not it needs to supply key handles to C_SetOperationState calls. If this flag is TRUE, then a call to C_SetOperationState never needs a key handle to be supplied to it. If this flag is FALSE, then at least some of the time, C_SetOperationState requires a key handle, and so the application should probably always pass in any relevant key handles when restoring cryptographic operations state to a session.

C_SetOperationState can successfully restore cryptographic operations state to a session even if that session has active cryptographic or object search operations when C_SetOperationState is called (the ongoing operations are abruptly cancelled).

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_KEY_CHANGED, CKR_KEY_NEEDED, CKR_KEY_NOT_NEEDED, CKR_SAVED_STATE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_MECHANISM digestMechanism;
CK_ULONG ulStateLen;
CK_BYTE data1[] = {0x01, 0x03, 0x05, 0x07};
CK_BYTE data2[] = {0x02, 0x04, 0x08};
CK_BYTE data3[] = {0x10, 0x0F, 0x0E, 0x0D, 0x0C};
CK_BYTE pDigest[20];
CK_ULONG ulDigestLen;
CK_RV rv;
.
.
.
/* Initialize hash operation */
rv = C_DigestInit(hSession, &digestMechanism);
assert(rv == CKR_OK);
/* Start hashing */
rv = C_DigestUpdate(hSession, data1, sizeof(data1));
assert(rv == CKR_OK);
/* Find out how big the state might be */
rv = C_GetOperationState(hSession, NULL_PTR, &ulStateLen);
assert(rv == CKR_OK);
/* Allocate some memory and then get the state */
pState = (CK_BYTE_PTR) malloc(ulStateLen);
rv = C_GetOperationState(hSession, pState, &ulStateLen);
/* Continue hashing */
rv = C_DigestUpdate(hSession, data2, sizeof(data2));
assert(rv == CKR_OK);
/* Restore state. No key handles needed */
rv = C_SetOperationState(hSession, pState, ulStateLen, 0, 0);
assert(rv == CKR_OK);
/* Continue hashing from where we saved state */
rv = C_DigestUpdate(hSession, data3, sizeof(data3));
assert(rv == CKR_OK);
/* Conclude hashing operation */
ulDigestLen = sizeof(pDigest);
rv = C_DigestFinal(hSession, pDigest, &ulDigestLen);
if (rv == CKR_OK) {
/* pDigest[] now contains the hash of 0x01030507100F0E0D0C */
.
.
.
}

C_Login

CK_RV C_Login(
CK_SESSION_HANDLE hSession,
CK_USER_TYPE userType,
CK_CHAR_PTR pPin,
CK_ULONG ulPinLen
);

C_Login logs a user into a token.

Parameters:
hSession is a session handle;
userType is the user type;
pPin points to the user's PIN; ulPinLen is the length of the PIN.
Depending on the user type, if the call succeeds, each of the application's sessions will enter either the "R/W SO Functions" state, the "R/W User Functions" state, or the "R/O User Functions" state.

If the token has a "protected authentication path", as indicated by the CKR_PROTECTED_AUTHENTICATION_PATH flag in its CK_TOKEN_INFO being set, then that means that there is some way for a user to be authenticated to the token without having the application send a PIN through the Cryptoki library. One such possibility is that the user enters a PIN on a PINpad on the token itself, or on the slot device. Or the user might not even use a PIN"authentication could be achieved by some fingerprint-reading device, for example. To log into a token with a protected authentication path, the pPin parameter to C_Login should be NULL_PTR. When C_Login returns, whatever authentication method supported by the token will have been performed; a return value of CKR_OK means that the user was successfully authenticated, and a return value of CKR_PIN_INCORRECT means that the user was denied access.

If there are any active cryptographic or object finding operations in a session, and then C_Login is successfully executed, it may or may not be the case that those operations are still active. Therefore, before logging in, any active operations should be finished.

If the application calling C_Login has a R/O session open with the token, then it will be unable to log the SO into a session (see Section). An attempt to do this will result in the error code CKR_SESSION_READ_ONLY_EXISTS.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_PIN_INCORRECT, CKR_SESSION_READ_ONLY_EXISTS, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_ALREADY_LOGGED_IN, CKR_USER_PIN_NOT_INITIALIZED, CKR_USER_TYPE_INVALID.
See also:
C_Logout.

C_Logout

CK_RV C_Logout(
CK_SESSION_HANDLE hSession
);

C_Logout logs a user out from a token.

Parameters:
hSession is the session's handle.
Depending on the current user type, if the call succeeds, each of the application's sessions will enter either the "R/W Public Session" state or the "R/O Public Session" state.

When C_Logout successfully executes, any of the application's handles to private objects become invalid (even if a user is later logged back into the token, those handles remain invalid). In addition, all private session objects are destroyed.

If there are any active cryptographic or object finding operations in a session, and then C_Logout is successfully executed, it may or may not be the case that those operations are still active. Therefore, before logging out, any active operations should be finished.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_CHAR userPIN[] = {"MyPIN"};
CK_RV rv;
rv = C_Login(hSession, CKU_USER, userPIN, sizeof(userPIN));
if (rv == CKR_OK) {
.
.
.
rv == C_Logout(hSession);
if (rv == CKR_OK) {
.
.
.
}
}

Object management functions

Cryptoki provides the following functions for managing objects. These functions do not run in parallel with the application. Additional functions provided specifically for managing key objects are described in Section .

C_CreateObject

CK_RV C_CreateObject(
CK_SESSION_HANDLE hSession,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR phObject
);

C_CreateObject creates a new object.

Parameters:
hSession is the session's handle;
pTemplate points to the object's template;
ulCount is the number of attributes in the template;
phObject points to the location that receives the new object's handle.
If C_CreateObject is used to create a key object, the key object will have its CKA_LOCAL attribute set to FALSE.

Only session object can be created during a read-only session. Only public objects can be created unless the normal user is logged in.

Returns:
CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE
hData,
hCertificate,
hKey;
CK_OBJECT_CLASS
dataClass = CKO_DATA,
certificateClass = CKO_CERTIFICATE,
keyClass = CKO_PUBLIC_KEY;
CK_KEY_TYPE keyType = CKK_RSA;
CK_CHAR application[] = {"My Application"};
CK_BYTE dataValue[] = {...};
CK_BYTE subject[] = {...};
CK_BYTE id[] = {...};
CK_BYTE certificateValue[] = {...};
CK_BYTE modulus[] = {...};
CK_BYTE exponent[] = {...};
CK_BYTE true = TRUE;
CK_ATTRIBUTE dataTemplate[] = {
{CKA_CLASS, &dataClass, sizeof(dataClass)},
{CKA_TOKEN, &true, sizeof(true)},
{CKA_APPLICATION, application, sizeof(application)},
{CKA_VALUE, dataValue, sizeof(dataValue)}
};
CK_ATTRIBUTE certificateTemplate[] = {
{CKA_CLASS, &certificateClass, sizeof(certificateClass)},
{CKA_TOKEN, &true, sizeof(true)},
{CKA_SUBJECT, subject, sizeof(subject)},
{CKA_ID, id, sizeof(id)},
{CKA_VALUE, certificateValue, sizeof(certificateValue)}
};
CK_ATTRIBUTE keyTemplate[] = {
{CKA_CLASS, &keyClass, sizeof(keyClass)},
{CKA_KEY_TYPE, &keyType, sizeof(keyType)},
{CKA_WRAP, &true, sizeof(true)},
{CKA_MODULUS, modulus, sizeof(modulus)},
{CKA_PUBLIC_EXPONENT, exponent, sizeof(exponent)}
};
CK_RV rv;
.
.
.
/* Create a data object */
rv = C_CreateObject(hSession, &dataTemplate, 4, &hData);
if (rv == CKR_OK) {
.
.
.
}
/* Create a certificate object */
rv = C_CreateObject(
hSession, &certificateTemplate, 5, &hCertificate);
if (rv == CKR_OK) {
.
.
.
}
/* Create an RSA private key object */
rv = C_CreateObject(hSession, &keyTemplate, 5, &hKey);
if (rv == CKR_OK) {
.
.
.
}

C_CopyObject

CK_RV C_CopyObject(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR phNewObject
);

C_CopyObject copies an object, creating a new object for the copy.

Parameters:
hSession is the session's handle;
hObject is the object's handle;
pTemplate points to the template for the new object;
ulCount is the number of attributes in the template;
phNewObject points to the location that receives the handle for the copy of the object.
The template may specify new values for any attributes of the object that can ordinarily be modified (e.g., in the course of copying a secret key, a key's CKA_EXTRACTABLE attribute may be changed from TRUE to FALSE, but not the other way around. If this change is made, the new key's CKA_NEVER_EXTRACTABLE attribute will have the value FALSE. Similarly, the template may specify that the new key's CKA_SENSITIVE attribute be TRUE; the new key will have the same value for its CKA_ALWAYS_SENSITIVE attribute as the original key). It may also specify new values of the CKA_TOKEN and CKA_PRIVATE attributes (e.g., to copy a session object to a token object). If the template specifies a value of an attribute which is incompatible with other existing attributes of the object, the call fails with the return code CKR_TEMPLATE_INCONSISTENT.

Only session objects can be created during a read-only session. Only public objects can be created unless the normal user is logged in.

Returns:
CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OBJECT_HANDLE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey, hNewKey;
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_DES;
CK_BYTE id[] = {...};
CK_BYTE keyValue[] = {...};
CK_BYTE false = FALSE;
CK_BYTE true = TRUE;
CK_ATTRIBUTE keyTemplate[] = {
{CKA_CLASS, &keyClass, sizeof(keyClass)},
{CKA_KEY_TYPE, &keyType, sizeof(keyType)},
{CKA_TOKEN, &false, sizeof(false)},
{CKA_ID, id, sizeof(id)},
{CKA_VALUE, keyValue, sizeof(keyValue)}
};
CK_ATTRIBUTE copyTemplate[] = {
{CKA_TOKEN, &true, sizeof(true)}
};
CK_RV rv;
.
.
.
/* Create a DES secret key session object */
rv = C_CreateObject(hSession, &keyTemplate, 5, &hKey);
if (rv == CKR_OK) {
/* Create a copy which is a token object */
rv = C_CopyObject(hSession, hKey, &copyTemplate, 1, &hNewKey);
.
.
.
}

C_DestroyObject

CK_RV C_DestroyObject(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject
);

C_DestroyObject destroys an object.

Parameters:
hSession is the session's handle;
hObject is the object's handle.
Only session objects can be destroyed during a read-only session. Only public objects can be destroyed unless the normal user is logged in.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OBJECT_HANDLE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TOKEN_WRITE_PROTECTED.
See also:
C_GetObjectSize.

C_GetObjectSize

CK_RV C_GetObjectSize(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,
CK_ULONG_PTR pulSize
);

C_GetObjectSize gets the size of an object in bytes.

Parameters:
hSession is the session's handle;
hObject is the object's handle;
pulSize points to the location that receives the size in bytes of the object.
Cryptoki does not specify what the meaning of an object's size is. Intuitively, it is some measure of how much token memory the object takes up. If an application deletes (say) a private object of size S, it might be reasonable to assume that the ulFreePrivateMemory field of the token's CK_TOKEN_INFO structure increases by approximately S.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_INFORMATION_SENSITIVE, CKR_OBJECT_HANDLE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hObject;
CK_OBJECT_CLASS dataClass = CKO_DATA;
CK_CHAR application[] = {"My Application"};
CK_BYTE dataValue[] = {...};
CK_BYTE value[] = {...};
CK_BYTE true = TRUE;
CK_ATTRIBUTE template[] = {
{CKA_CLASS, &dataClass, sizeof(dataClass)},
{CKA_TOKEN, &true, sizeof(true)},
{CKA_APPLICATION, application, sizeof(application)},
{CKA_VALUE, value, sizeof(value)}
};
CK_ULONG ulSize;
CK_RV rv;
.
.
.
rv = C_CreateObject(hSession, &template, 4, &hObject);
if (rv == CKR_OK) {
rv = C_GetObjectSize(hSession, hObject, &ulSize);
if (rv != CKR_INFORMATION_SENSITIVE) {
.
.
.
}
rv = C_DestroyObject(hSession, hObject);
.
.
.
}

C_GetAttributeValue

CK_RV C_GetAttributeValue(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount
);

C_GetAttributeValue obtains the value of one or more attributes of an object.

Parameters:
hSession is the session's handle;
hObject is the object's handle;
pTemplate points to a template that specifies which attribute values are to be obtained, and receives the attribute values;
ulCount is the number of attributes in the template.
For each (type, pValue, ulValueLen) triple in the template, C_GetAttributeValue performs the following algorithm:

  1. If the specified attribute (i.e., the attribute specified by the type field) for the object cannot be revealed because the object is sensitive or nonextractable, then the ulValueLen field in that triple is modified to hold the value -1 (i.e., when it is cast to a CK_LONG, it holds -1).

  2. Otherwise, if the specified attribute for the object is invalid (the object does not possess such an attribute), then the ulValueLen field in that triple is modified to hold the value -1.

  3. Otherwise, if the pValue field has the value NULL_PTR, then the ulValueLen field is modified to hold the exact length of the specified attribute for the object.

  4. Otherwise, if the length specified in ulValueLen is large enough to hold the value of the specified attribute for the object, then that attribute is copied into the buffer located at pValue, and the ulValueLen field is modified to hold the exact length of the attribute.

  5. Otherwise, the ulValueLen field is modified to hold the value -1.

If case 1 applies to any of the requested attributes, then the call should return the value CKR_ATTRIBUTE_SENSITIVE. If case 2 applies to any of the requested attributes, then the call should return the value CKR_ATTRIBUTE_TYPE_INVALID. If case 5 applies to any of the requested attributes, then the call should return the value CKR_BUFFER_TOO_SMALL. As usual, if more than one of these error codes is applicable, Cryptoki may return any of them. Only if none of them applies to any of the requested attributes will CKR_OK be returned.

Returns:
CKR_ATTRIBUTE_SENSITIVE, CKR_ATTRIBUTE_TYPE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OBJECT_HANDLE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hObject;
CK_BYTE_PTR pModulus, pExponent;
CK_ATTRIBUTE template[] = {
{CKA_MODULUS, NULL_PTR, 0},
{CKA_PUBLIC_EXPONENT, NULL_PTR, 0}
};
CK_RV rv;
.
.
.
rv = C_GetAttributeValue(hSession, hObject, &template, 2);
if (rv == CKR_OK) {
pModulus = (CK_BYTE_PTR) malloc(template[0].ulValueLen);
template[0].pValue = pModulus;
/* template[0].ulValueLen was set by C_GetAttributeValue */
pExponent = (CK_BYTE_PTR) malloc(template[1].ulValueLen);
template[1].pValue = pExponent;
/* template[1].ulValueLen was set by C_GetAttributeValue */
rv = C_GetAttributeValue(hSession, hObject, &template, 2);
if (rv == CKR_OK) {
.
.
.
}
free(pModulus);
free(pExponent);
}

C_SetAttributeValue

CK_RV C_SetAttributeValue(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hObject,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount
);

C_SetAttributeValue modifies the value of one or more attributes of an object.

Parameters:
hSession is the session's handle;
hObject is the object's handle;
pTemplate points to a template that specifies which attribute values are to be modified and their new values;
ulCount is the number of attributes in the template.
Only session objects can be modified during a read-only session.

The template may specify new values for any attributes of the object that can be modified. If the template specifies a value of an attribute which is incompatible with other existing attributes of the object, the call fails with the return code CKR_TEMPLATE_INCONSISTENT.

Not all attributes can be modified; see Section for more details.

Returns:
CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OBJECT_HANDLE_INVALID, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hObject;
CK_CHAR label[] = {"New label"};
CK_ATTRIBUTE template[] = {
CKA_LABEL, label, sizeof(label)
};
CK_RV rv;
.
.
.
rv = C_SetAttributeValue(hSession, hObject, &template, 1);
if (rv == CKR_OK) {
.
.
.
}

C_FindObjectsInit

CK_RV C_FindObjectsInit(
CK_SESSION_HANDLE hSession,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount
);

C_FindObjectsInit initializes a search for token and session objects that match a template.

Parameters:
hSession is the session's handle;
pTemplate points to a search template that specifies the attribute values to match;
ulCount is the number of attributes in the search template. The matching criterion is an exact byte-for-byte match with all attributes in the template. To find all objects, set ulCount to 0.
After calling C_FindObjectsInit, the application may call C_FindObjects one or more times to obtain handles for objects matching the template, and then eventually call C_FindObjectsFinal to finish the active search operation. At most one search operation may be active at a given time in a given session.

The object search operation will only find objects that the session can view. For example, an object search in an "R/W Public Session" will not find any private objects (even if one of the attributes in the search template specifies that the search is for private objects).

If a search operation is active, and objects are created or destroyed which fit the search template for the active search operation, then those objects may or may not be found by the search operation. Note that this means that, under these circumstances, the search operation may return invalid object handles.

Even though C_FindObjectsInit can return the values CKR_ATTRIBUTE_TYPE_INVALID and CKR_ATTRIBUTE_VALUE_INVALID, it is not required to. For example, if it is given a search template with nonexistent attributes in it, it can return CKR_ATTRIBUTE_TYPE_INVALID, or it can return CKR_OK and initialize a search operation which will match no objects.

Returns:
CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_FindObjectsFinal.

C_FindObjects

CK_RV C_FindObjects(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE_PTR phObject,CK_ULONG ulMaxObjectCount,
CK_ULONG_PTR pulObjectCount
);

C_FindObjects continues a search for token and session objects that match a template, obtaining additional object handles.

Parameters:
hSession is the session's handle;
phObject points to the location that receives the list (array) of additional object handles;
ulMaxObjectCount is the maximum number of object handles to be returned;
pulObjectCount points to the location that receives the actual number of object handles returned.
If there are no more objects matching the template, then the location that pulObjectCount points to receives the value 0.

The search must have been initialized with C_FindObjectsInit.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_FindObjectsFinal.

C_FindObjectsFinal

CK_RV C_FindObjectsFinal(
CK_SESSION_HANDLE hSession
);

C_FindObjectsFinal terminates a search for token and session objects.

Parameters:
hSession is the session's handle.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hObject;
CK_ULONG ulObjectCount;
CK_RV rv;
.
.
.
rv = C_FindObjectsInit(hSession, NULL_PTR, 0);
assert(rv == CKR_OK);
while (1) {
rv = C_FindObjects(hSession, &hObject, 1, &ulObjectCount);
if (rv != CKR_OK || ulObjectCount == 0)
break;
.
.
.
}
rv = C_FindObjectsFinal(hSession);
assert(rv == CKR_OK);

Encryption functions

Cryptoki provides the following functions for encrypting data. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_EncryptInit

CK_RV C_EncryptInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_EncryptInit initializes an encryption operation.

Parameters:
hSession is the session's handle;
pMechanism points to the encryption mechanism;
hKey is the handle of the encryption key.
The CKA_ENCRYPT attribute of the encryption key, which indicates whether the key supports encryption, must be TRUE.

After calling C_EncryptInit, the application can either call C_Encrypt to encrypt data in a single part; or call C_EncryptUpdate zero or more times, followed by C_EncryptFinal, to encrypt data in multiple parts. The encryption operation is active until the application uses a call to C_Encrypt or C_EncryptFinal to actually obtain the final piece of ciphertext. To process additional data (in single or multiple parts), the application must call C_EncryptInit again.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_EncryptFinal.

C_Encrypt

CK_RV C_Encrypt(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pEncryptedData,
CK_ULONG_PTR pulEncryptedDataLen
);

C_Encrypt encrypts single-part data.

Parameters:
hSession is the session's handle;
pData points to the data;
ulDataLen is the length in bytes of the data;
pEncryptedData points to the location that receives the encrypted data;
pulEncryptedDataLen points to the location that holds the length in bytes of the encrypted data.
C_Encrypt uses the convention described in Section on producing output.

The encryption operation must have been initialized with C_EncryptInit. A call to C_Encrypt always terminates the active encryption operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the ciphertext.

For some encryption mechanisms, the input plaintext data has certain length constraints (either because the mechanism can only encrypt relatively short pieces of plaintext, or because the mechanism's input data must consist of an integral number of blocks). If these constraints are not satisfied, then C_Encrypt will fail with return code CKR_DATA_LEN_RANGE.

The plaintext and ciphertext can be in the same place, i.e., it is OK if pData and pEncryptedData point to the same location.

C_Encrypt is equivalent to a sequence of C_EncryptUpdate and C_EncryptFinal.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_EncryptFinal for an example of similar functions.

C_EncryptUpdate

CK_RV C_EncryptUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen
);

C_EncryptUpdate continues a multiple-part encryption operation, processing another data part.

Parameters:
hSession is the session's handle;
pPart points to the data part;
ulPartLen is the length of the data part;
pEncryptedPart points to the location that receives the encrypted data part;
pulEncryptedPartLen points to the location that holds the length in bytes of the encrypted data part.
C_EncryptUpdate uses the convention described in Section on producing output.

The encryption operation must have been initialized with C_EncryptInit. This function may be called any number of times in succession. A call to C_EncryptUpdate which results in an error other than CKR_BUFFER_TOO_SMALL terminates the current encryption operation.

The encryption operation must have been initialized with C_EncryptInit. A call to C_Encrypt always terminates the active encryption operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the ciphertext.

The plaintext and ciphertext can be in the same place, i.e., it is OK if pPart and pEncryptedPart point to the same location.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_EncryptFinal.'''

C_EncryptFinal

CK_RV C_EncryptFinal(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pLastEncryptedPart,
CK_ULONG_PTR pulLastEncryptedPartLen
);

C_EncryptFinal finishes a multiple-part encryption operation.

Parameters:
hSession is the session's handle;
pLastEncryptedPart points to the location that receives the last encrypted data part, if any;
pulLastEncryptedPartLen points to the location that holds the length of the last encrypted data part.
C_EncryptFinal uses the convention described in Section on producing output.

The encryption operation must have been initialized with C_EncryptInit. A call to C_EncryptFinal always terminates the active encryption operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the ciphertext.

For some multi-part encryption mechanisms, the input plaintext data has certain length constraints, because the mechanism's input data must consist of an integral number of blocks. If these constraints are not satisfied, then C_EncryptFinal will fail with return code CKR_DATA_LEN_RANGE.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define PLAINTEXT_BUF_SZ 200
#define CIPHERTEXT_BUF_SZ 256
CK_ULONG firstPieceLen, secondPieceLen;
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_BYTE iv[8];
CK_MECHANISM mechanism = {
CKM_DES_CBC_PAD, iv, sizeof(iv)
};
CK_BYTE data[PLAINTEXT_BUF_SZ];
CK_BYTE encryptedData[CIPHERTEXT_BUF_SZ];
CK_ULONG ulEncryptedData1Len;
CK_ULONG ulEncryptedData2Len;
CK_ULONG ulEncryptedData3Len;
CK_RV rv;
.
.
.
firstPieceLen = 90;
secondPieceLen = PLAINTEXT_BUF_SZ-firstPieceLen;
rv = C_EncryptInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
/* Encrypt first piece */
ulEncryptedData1Len = sizeof(encryptedData);
rv = C_EncryptUpdate(
hSession,
&data[0], firstPieceLen,
&encryptedData[0], &ulEncryptedData1Len);
if (rv != CKR_OK) {
.
.
.
}
/* Encrypt second piece */
ulEncryptedData2Len = sizeof(encryptedData)-ulEncryptedData1Len;
rv = C_EncryptUpdate(
hSession,
&data[firstPieceLen], secondPieceLen,
&encryptedData[ulEncryptedData1Len], &ulEncryptedData2Len);
if (rv != CKR_OK) {
.
.
.
}
/* Get last little encrypted bit */
ulEncryptedData3Len =
sizeof(encryptedData)
-ulEncryptedData1Len-ulEncryptedData2Len;
rv = C_EncryptFinal(
hSession,
&encryptedData[ulEncryptedData1Len+ulEncryptedData2Len],
&ulEncryptedData3Len);
if (rv != CKR_OK) {
.
.
.
}
}

Decryption functions

Cryptoki provides the following functions for decrypting data. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_DecryptInit

CK_RV C_DecryptInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_DecryptInit initializes a decryption operation.

Parameters:
hSession is the session's handle;
pMechanism points to the decryption mechanism;
hKey is the handle of the decryption key.
The CKA_DECRYPT attribute of the decryption key, which indicates whether the key supports decryption, must be TRUE.

After calling C_DecryptInit, the application can either call C_Decrypt to decrypt data in a single part; or call C_DecryptUpdate zero or more times, followed by C_DecryptFinal, to decrypt data in multiple parts. The decryption operation is active until the application uses a call to C_Decrypt or C_DecryptFinal to actually obtain the final piece of plaintext. To process additional data (in single or multiple parts), the application must call C_DecryptInit again

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_DecryptFinal.

C_Decrypt

CK_RV C_Decrypt(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pEncryptedData,
CK_ULONG ulEncryptedDataLen,
CK_BYTE_PTR pData,
CK_ULONG_PTR pulDataLen
);

C_Decrypt decrypts encrypted data in a single part.

Parameters:
hSession is the session's handle;
pEncryptedData points to the encrypted data;
ulEncryptedDataLen is the length of the encrypted data;
pData points to the location that receives the recovered data;
pulDataLen points to the location that holds the length of the recovered data.
C_Decrypt uses the convention described in Section on producing output.

The decryption operation must have been initialized with C_DecryptInit. A call to C_Decrypt always terminates the active decryption operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the plaintext.

The ciphertext and plaintext can be in the same place, i.e., it is OK if pEncryptedData and pData point to the same location.

If the input ciphertext data cannot be decrypted because it has an inappropriate length, then either CKR_ENCRYPTED_DATA_INVALID or CKR_ENCRYPTED_DATA_LEN_RANGE may be returned.

C_Decrypt is equivalent to a sequence of C_DecryptUpdate and C_DecryptFinal.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_DecryptFinal for an example of similar functions.

C_DecryptUpdate

CK_RV C_DecryptUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG ulEncryptedPartLen,
CK_BYTE_PTR pPart,
CK_ULONG_PTR pulPartLen
);

C_DecryptUpdate continues a multiple-part decryption operation, processing another encrypted data part.

Parameters:
hSession is the session's handle;
pEncryptedPart points to the encrypted data part;
ulEncryptedPartLen is the length of the encrypted data part;
pPart points to the location that receives the recovered data part;
pulPartLen points to the location that holds the length of the recovered data part.
C_DecryptUpdate uses the convention described in Section on producing output.

The decryption operation must have been initialized with C_DecryptInit. This function may be called any number of times in succession. A call to C_DecryptUpdate which results in an error other than CKR_BUFFER_TOO_SMALL terminates the current decryption operation.

The ciphertext and plaintext can be in the same place, i.e., it is OK if pEncryptedPart and pPart point to the same location.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_DecryptFinal.

C_DecryptFinal

CK_RV C_DecryptFinal(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pLastPart,
CK_ULONG_PTR pulLastPartLen
);

C_DecryptFinal finishes a multiple-part decryption operation.

Parameters:
hSession is the session's handle;
pLastPart points to the location that receives the last recovered data part, if any;
pulLastPartLen points to the location that holds the length of the last recovered data part.
C_DecryptFinal uses the convention described in Section on producing output.

The decryption operation must have been initialized with C_DecryptInit. A call to C_DecryptFinal always terminates the active decryption operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the plaintext.

If the input ciphertext data cannot be decrypted because it has an inappropriate length, then either CKR_ENCRYPTED_DATA_INVALID or CKR_ENCRYPTED_DATA_LEN_RANGE may be returned.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define CIPHERTEXT_BUF_SZ 256
#define PLAINTEXT_BUF_SZ 256
CK_ULONG firstEncryptedPieceLen, secondEncryptedPieceLen;
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_BYTE iv[8];
CK_MECHANISM mechanism = {
CKM_DES_CBC_PAD, iv, sizeof(iv)
};
CK_BYTE data[PLAINTEXT_BUF_SZ];
CK_BYTE encryptedData[CIPHERTEXT_BUF_SZ];
CK_ULONG ulData1Len, ulData2Len, ulData3Len;
CK_RV rv;
.
.
.
firstEncryptedPieceLen = 90;
secondEncryptedPieceLen = CIPHERTEXT_BUF_SZ-firstEncryptedPieceLen;
rv = C_DecryptInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
/* Decrypt first piece */
ulData1Len = sizeof(data);
rv = C_DecryptUpdate(
hSession,
&encryptedData[0], firstEncryptedPieceLen,
&data[0], &ulData1Len);
if (rv != CKR_OK) {
.
.
.
}
/* Decrypt second piece */
ulData2Len = sizeof(data)-ulData1Len;
rv = C_DecryptUpdate(
hSession,
&encryptedData[firstEncryptedPieceLen],
secondEncryptedPieceLen,
&data[ulData1Len], &ulData2Len);
if (rv != CKR_OK) {
.
.
.
}
/* Get last little decrypted bit */
ulData3Len = sizeof(data)-ulData1Len-ulData2Len;
rv = C_DecryptFinal(
hSession,
&data[ulData1Len+ulData2Len], &ulData3Len);
if (rv != CKR_OK) {
.
.
.
}
}

Message digesting functions

Cryptoki provides the following functions for digesting data. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_DigestInit

CK_RV C_DigestInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism
);

C_DigestInit initializes a message-digesting operation.

Parameters:
hSession is the session's handle;
pMechanism points to the digesting mechanism.
After calling C_DigestInit, the application can either call C_Digest to digest data in a single part; or call C_DigestUpdate zero or more times, followed by C_DigestFinal, to digest data in multiple parts. The message-digesting operation is active until the application uses a call to C_Digest or C_DigestFinal to actually obtain the final piece of ciphertext. To process additional data (in single or multiple parts), the application must call C_DigestInit again.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_DigestFinal.

C_Digest

CK_RV C_Digest(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pDigest,
CK_ULONG_PTR pulDigestLen
);

C_Digest digests data in a single part.

Parameters:
hSession is the session's handle, pData points to the data;
ulDataLen is the length of the data;
pDigest points to the location that receives the message digest;
pulDigestLen points to the location that holds the length of the message digest.
C_Digest uses the convention described in Section on producing output.

The digest operation must have been initialized with C_DigestInit. A call to C_Digest always terminates the active digest operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the message digest.

The input data and digest output can be in the same place, i.e., it is OK if pData and pDigest point to the same location.

C_Digest is equivalent to a sequence of C_DigestUpdate and C_DigestFinal.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_DigestFinal for an example of similar functions.

C_DigestUpdate

CK_RV C_DigestUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen
);

C_DigestUpdate continues a multiple-part message-digesting operation, processing another data part.

Parameters:
hSession is the session's handle, pPart points to the data part;
ulPartLen is the length of the data part.
The message-digesting operation must have been initialized with C_DigestInit. Calls to this function and C_DigestKey may be interspersed any number of times in any order. A call to C_DigestUpdate which results in an error terminates the current digest operation.

Returns:
CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_DigestFinal.

C_DigestKey

CK_RV C_DigestKey(
CK_SESSION_HANDLE hSession,
CK_OBJECT_HANDLE hKey
);

C_DigestKey continues a multiple-part message-digesting operation by digesting the value of a secret key.

Parameters:
hSession is the session's handle;
hKey is the handle of the secret key to be digested.
The message-digesting operation must have been initialized with C_DigestInit. Calls to this function and C_DigestUpdate may be interspersed any number of times in any order.

If the value of the supplied key cannot be digested purely for some reason related to its length, C_DigestKey should return the error code CKR_KEY_SIZE_RANGE.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_INDIGESTIBLE, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_DigestFinal.

C_DigestFinal

CK_RV C_DigestFinal(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pDigest,
CK_ULONG_PTR pulDigestLen
);

C_DigestFinal finishes a multiple-part message-digesting operation, returning the message digest.

Parameters:
hSession is the session's handle;
pDigest points to the location that receives the message digest;
pulDigestLen points to the location that holds the length of the message digest.
C_DigestFinal uses the convention described in Section on producing output.

The digest operation must have been initialized with C_DigestInit. A call to C_DigestFinal always terminates the active digest operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the message digest.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_MECHANISM mechanism = {
CKM_MD5, NULL_PTR, 0
};
CK_BYTE data[] = {...};
CK_BYTE digest[16];
CK_ULONG ulDigestLen;
CK_RV rv;
.
.
.
rv = C_DigestInit(hSession, &mechanism);
if (rv != CKR_OK) {
.
.
.
}
rv = C_DigestUpdate(hSession, data, sizeof(data));
if (rv != CKR_OK) {
.
.
.
}
rv = C_DigestKey(hSession, hKey);
if (rv != CKR_OK) {
.
.
.
}
ulDigestLen = sizeof(digest);
rv = C_DigestFinal(hSession, digest, &ulDigestLen);
.
.
.

Signing and MACing functions

Cryptoki provides the following functions for signing data (for the purposes of Cryptoki, these operations also encompass message authentication codes). All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_SignInit

CK_RV C_SignInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_SignInit initializes a signature operation, where the signature is an appendix to the data.

Parameters:
hSession is the session's handle;
pMechanism points to the signature mechanism;
hKey is the handle of the signature key.
The CKA_SIGN attribute of the signature key, which indicates whether the key supports signatures with appendix, must be TRUE.

After calling C_SignInit, the application can either call C_Sign to sign in a single part; or call C_SignUpdate one or more times, followed by C_SignFinal, to sign data in multiple parts. The signature operation is active until the application uses a call to C_Sign or C_SignFinal to actually obtain the signature. To process additional data (in single or multiple parts), the application must call C_SignInit again.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_SignFinal.

C_Sign

CK_RV C_Sign(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pSignature,
CK_ULONG_PTR pulSignatureLen
);

C_Sign signs data in a single part, where the signature is an appendix to the data.

Parameters:
hSession is the session's handle;
pData points to the data;
ulDataLen is the length of the data;
pSignature points to the location that receives the signature;
pulSignatureLen points to the location that holds the length of the signature.
C_Sign uses the convention described in Section on producing output.

The signing operation must have been initialized with C_SignInit. A call to C_Sign always terminates the active signing operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the signature.

C_Sign is equivalent to a sequence of C_SignUpdate and C_SignFinal.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_SignFinal for an example of similar functions.

C_SignUpdate

CK_RV C_SignUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen
);

C_SignUpdate continues a multiple-part signature operation, processing another data part.

Parameters:
hSession is the session's handle, pPart points to the data part;
ulPartLen is the length of the data part.
The signature operation must have been initialized with C_SignInit. This function may be called any number of times in succession. A call to C_SignUpdate which results in an error terminates the current signature operation.

Returns:
CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_SignFinal.

C_SignFinal

CK_RV C_SignFinal(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pSignature,
CK_ULONG_PTR pulSignatureLen
);

C_SignFinal finishes a multiple-part signature operation, returning the signature.

Parameters:
hSession is the session's handle;
pSignature points to the location that receives the signature;
pulSignatureLen points to the location that holds the length of the signature.
C_SignFinal uses the convention described in Section on producing output.

The signing operation must have been initialized with C_SignInit. A call to C_SignFinal always terminates the active signing operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the signature.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_MECHANISM mechanism = {
CKM_DES_MAC, NULL_PTR, 0
};
CK_BYTE data[] = {...};
CK_BYTE mac[4];
CK_ULONG ulMacLen;
CK_RV rv;
.
.
.
rv = C_SignInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
rv = C_SignUpdate(hSession, data, sizeof(data));
.
.
.
ulMacLen = sizeof(mac);
rv = C_SignFinal(hSession, mac, &ulMacLen);
.
.
.
}

C_SignRecoverInit

CK_RV C_SignRecoverInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_SignRecoverInit initializes a signature operation, where the data can be recovered from the signature.

Parameters:
hSession is the session's handle;
pMechanism points to the structure that specifies the signature mechanism;
hKey is the handle of the signature key.
The CKA_SIGN_RECOVER attribute of the signature key, which indicates whether the key supports signatures where the data can be recovered from the signature, must be TRUE.

After calling C_SignRecoverInit, the application may call C_SignRecover to sign in a single part. The signature operation is active until the application uses a call to C_SignRecover to actually obtain the signature. To process additional data in a single part, the application must call C_SignRecoverInit again.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_ACTIVE, CKR_USER_NOT_LOGGED_IN.
See also:
C_SignRecover.

C_SignRecover

CK_RV C_SignRecover(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pSignature,
CK_ULONG_PTR pulSignatureLen
);

C_SignRecover signs data in a single operation, where the data can be recovered from the signature.

Parameters:
hSession is the session's handle;
pData points to the data;
ulDataLen is the length of the data;
pSignature points to the location that receives the signature;
pulSignatureLen points to the location that holds the length of the signature.
C_SignRecover uses the convention described in Section on producing output.

The signing operation must have been initialized with C_SignRecoverInit. A call to C_SignRecover always terminates the active signing operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the signature.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_ACTIVE.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_MECHANISM mechanism = {
CKM_RSA_9796, NULL_PTR, 0
};
CK_BYTE data[] = {...};
CK_BYTE signature[128];
CK_ULONG ulSignatureLen;
CK_RV rv;
.
.
.
rv = C_SignRecoverInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
usSignatureLen = sizeof(signature);
rv = C_SignRecover(
hSession, data, sizeof(data), signature, &usSignatureLen);
if (rv == CKR_OK) {
.
.
.
}
}

Functions for verifying signatures and MACs

Cryptoki provides the following functions for verifying signatures on data (for the purposes of Cryptoki, these operations also encompass message authentication codes). All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_VerifyInit

CK_RV C_VerifyInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_VerifyInit initializes a verification operation, where the signature is an appendix to the data.

Parameters:
hSession is the session's handle;
pMechanism points to the structure that specifies the verification mechanism;
hKey is the handle of the verification key.
The CKA_VERIFY attribute of the verification key, which indicates whether the key supports verification where the signature is an appendix to the data, must be TRUE.

After calling C_VerifyInit, the application can either call C_Verify to verify a signature on data in a single part; or call C_VerifyUpdate one or more times, followed by C_VerifyFinal, to verify a signature on data in multiple parts. The verification operation is active until the application calls C_Verify or C_VerifyFinal. To process additional data (in single or multiple parts), the application must call C_VerifyInit again.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_VerifyFinal.

C_Verify

CK_RV C_Verify(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pData,
CK_ULONG ulDataLen,
CK_BYTE_PTR pSignature,
CK_ULONG ulSignatureLen
);

C_Verify verifies a signature in a single-part operation, where the signature is an appendix to the data.

Parameters:
hSession is the session's handle;
pData points to the data;
ulDataLen is the length of the data;
pSignature points to the signature;
ulSignatureLen is the length of the signature.
The verification operation must have been initialized with C_VerifyInit. A call to C_Verify always terminates the active verification operation.

A successful call to C_Verify should return either the value CKR_OK (indicating that the supplied signature is valid) or CKR_SIGNATURE_INVALID (indicating that the supplied signature is invalid). If the signature can be seen to be invalid purely on the basis of its length, then CKR_SIGNATURE_LEN_RANGE should be returned. In any of these cases, the active signing operation is terminated.

C_Verify is equivalent to a sequence of C_VerifyUpdate and C_VerifyFinal.

Returns:
CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE.
See also:
C_VerifyFinal for an example of similar functions.

C_VerifyUpdate

CK_RV C_VerifyUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen
);

C_VerifyUpdate continues a multiple-part verification operation, processing another data part.

Parameters:
hSession is the session's handle, pPart points to the data part;
ulPartLen is the length of the data part.
The verification operation must have been initialized with C_VerifyInit. This function may be called any number of times in succession. A call to C_VerifyUpdate which results in an error terminates the current verification operation.

Returns:
CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
See also:
C_VerifyFinal.

C_VerifyFinal

CK_RV C_VerifyFinal(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pSignature,
CK_ULONG ulSignatureLen
);

C_VerifyFinal finishes a multiple-part verification operation, checking the signature.

Parameters:
hSession is the session's handle;
pSignature points to the signature;
ulSignatureLen is the length of the signature.
The verification operation must have been initialized with C_VerifyInit. A call to C_VerifyFinal always terminates the active verification operation.

A successful call to C_VerifyFinal should return either the value CKR_OK (indicating that the supplied signature is valid) or CKR_SIGNATURE_INVALID (indicating that the supplied signature is invalid). If the signature can be seen to be invalid purely on the basis of its length, then CKR_SIGNATURE_LEN_RANGE should be returned. In any of these cases, the active verifying operation is terminated.

Returns:
CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_MECHANISM mechanism = {
CKM_DES_MAC, NULL_PTR, 0
};
CK_BYTE data[] = {...};
CK_BYTE mac[4];
CK_RV rv;
.
.
.
rv = C_VerifyInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
rv = C_VerifyUpdate(hSession, data, sizeof(data));
.
.
.
rv = C_VerifyFinal(hSession, mac, sizeof(mac));
.
.
.
}

C_VerifyRecoverInit

CK_RV C_VerifyRecoverInit(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hKey
);

C_VerifyRecoverInit initializes a signature verification operation, where the data is recovered from the signature.

Parameters:
hSession is the session's handle;
pMechanism points to the structure that specifies the verification mechanism;
hKey is the handle of the verification key.
The CKA_VERIFY_RECOVER attribute of the verification key, which indicates whether the key supports verification where the data is recovered from the signature, must be TRUE.

After calling C_VerifyRecoverInit, the application may call C_VerifyRecover to verify a signature on data in a single part. The verification operation is active until the application uses a call to C_VerifyRecover to actually obtain the recovered message.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
See also:
C_VerifyRecover.

C_VerifyRecover

CK_RV C_VerifyRecover(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pSignature,
CK_ULONG ulSignatureLen,
CK_BYTE_PTR pData,
CK_ULONG_PTR pulDataLen
);

C_VerifyRecover verifies a signature in a single-part operation, where the data is recovered from the signature.

Parameters:
hSession is the session's handle;
pSignature points to the signature;
ulSignatureLen is the length of the signature;
pData points to the location that receives the recovered data;
pulDataLen points to the location that holds the length of the recovered data.
C_VerifyRecover uses the convention described in Section on producing output.

The verification operation must have been initialized with C_VerifyRecoverInit. A call to C_VerifyRecover always terminates the active verification operation unless it returns CKR_BUFFER_TOO_SMALL or is a successful call (i.e., one which returns CKR_OK) to determine the length of the buffer needed to hold the recovered data.

A successful call to C_VerifyRecover should return either the value CKR_OK (indicating that the supplied signature is valid) or CKR_SIGNATURE_INVALID (indicating that the supplied signature is invalid). If the signature can be seen to be invalid purely on the basis of its length, then CKR_SIGNATURE_LEN_RANGE should be returned. The return codes CKR_SIGNATURE_INVALID and CKR_SIGNATURE_LEN_RANGE have a higher priority than the return code CKR_BUFFER_TOO_SMALL, i.e., if C_VerifyRecover is supplied with an invalid signature, it will never return CKR_BUFFER_TOO_SMALL.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_LEN_RANGE, CKR_SIGNATURE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_MECHANISM mechanism = {
CKM_RSA_9796, NULL_PTR, 0
};
CK_BYTE data[] = {...};
CK_ULONG ulDataLen;
CK_BYTE signature[128];
CK_RV rv;
.
.
.
rv = C_VerifyRecoverInit(hSession, &mechanism, hKey);
if (rv == CKR_OK) {
ulDataLen = sizeof(data);
rv = C_VerifyRecover(
hSession, signature, sizeof(signature), data, &ulDataLen);
.
.
.
}

Dual-function cryptographic functions

Cryptoki provides the following functions to perform two cryptographic operations "simultaneously" within a session. These functions are provided so as to avoid unnecessarily passing data back and forth to and from a token. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_DigestEncryptUpdate

CK_RV C_DigestEncryptUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen
);

C_DigestEncryptUpdate continues multiple-part digest and encryption operations, processing another data part.

Parameters:
hSession is the session's handle;
pPart points to the data part;
ulPartLen is the length of the data part;
pEncryptedPart points to the location that receives the digested and encrypted data part;
pulEncryptedPart points to the location that holds the length of the encrypted data part.
C_DigestEncryptUpdate uses the convention described in Section on producing output.

Digest and encryption operations must both be active (they must have been initialized with C_DigestInit and C_EncryptInit, respectively). This function may be called any number of times in succession, and may be interspersed with C_DigestUpdate, C_DigestKey, and C_EncryptUpdate calls (it would be somewhat unusual to intersperse calls to C_DigestEncryptUpdate with calls to C_DigestKey, however).

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define BUF_SZ 512
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_BYTE iv[8];
CK_MECHANISM digestMechanism = {
CKM_MD5, NULL_PTR, 0
};
CK_MECHANISM encryptionMechanism = {
CKM_DES_ECB, iv, sizeof(iv)
};
CK_BYTE encryptedData[BUF_SZ];
CK_ULONG ulEncryptedDataLen;
CK_BYTE digest[16];
CK_ULONG ulDigestLen;
CK_BYTE data[(2*BUF_SZ)+8];
CK_RV rv;
int i;
.
.
.
memset(iv, 0, sizeof(iv));
memset(data, 'A', ((2*BUF_SZ)+5));
rv = C_EncryptInit(hSession, &encryptionMechanism, hKey);
if (rv != CKR_OK) {
.
.
.
}
rv = C_DigestInit(hSession, &digestMechanism);
if (rv != CKR_OK) {
.
.
.
}
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_DigestEncryptUpdate(
hSession,
&data[0], BUF_SZ,
encryptedData, &ulEncryptedDataLen);
.
.
.
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_DigestEncryptUpdate(
hSession,
&data[BUF_SZ], BUF_SZ,
encryptedData, &ulEncryptedDataLen);
.
.
.
/*
* The last portion of the buffer needs to be handled with 
* separate calls to deal with padding issues in ECB mode
*/
/* First, complete the digest on the buffer */
rv = C_DigestUpdate(hSession, &data[BUF_SZ*2], 5);
.
.
.
ulDigestLen = sizeof(digest);
rv = C_DigestFinal(hSession, digest, &ulDigestLen);
.
.
.
/* Then, pad last part with 3 0x00 bytes, and complete encryption */
for(i=0;i<3;i++)
data[((BUF_SZ*2)+5)+i] = 0x00;
/* Now, get second-to-last piece of ciphertext */
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_EncryptUpdate(
hSession,
&data[BUF_SZ*2], 8,
encryptedData, &ulEncryptedDataLen);
.
.
.
/* Get last piece of ciphertext (should have length 0, here) */
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_EncryptFinal(hSession, encryptedData, &ulEncryptedDataLen);
.
.
.

C_DecryptDigestUpdate

CK_RV C_DecryptDigestUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG ulEncryptedPartLen,
CK_BYTE_PTR pPart,
CK_ULONG_PTR pulPartLen
);

C_DecryptDigestUpdate continues a multiple-part combined decryption and digest operation, processing another data part.

Parameters:
hSession is the session's handle;
pEncryptedData points to the encrypted data;
ulEncryptedDataLen is the length of the encrypted data;
pData points to the location that receives the recovered data;
pulDataLen points to the location that holds the length of the recovered data.
C_DecryptDigestUpdate uses the convention described in Section on producing output.

Decryption and digesting operations must both be active (they must have been initialized with C_DecryptInit and C_DigestInit, respectively). This function may be called any number of times in succession, and may be interspersed with C_DecryptUpdate, C_DigestUpdate, and C_DigestKey calls (it would be somewhat unusual to intersperse calls to C_DigestEncryptUpdate with calls to C_DigestKey, however).

Use of C_DecryptDigestUpdate involves a pipelining issue that does not arise when using C_DigestEncryptUpdate, the "inverse function" of C_DecryptDigestUpdate. This is because when C_DigestEncryptUpdate is called, precisely the same input is passed to both the active digesting operation and the active encryption operation; however, when C_DecryptDigestUpdate is called, the input passed to the active digesting operation is the output of the active decryption operation. This issue comes up only when the mechanism used for decryption performs padding.

In particular, envision a 24-byte ciphertext which was obtained by encrypting an 18-byte plaintext with DES in CBC mode with PKCS padding. Consider an application which will simultaneously decrypt this ciphertext and digest the original plaintext thereby obtained.

After initializing decryption and digesting operations, the application passes the 24-byte ciphertext (3 DES blocks) into C_DecryptDigestUpdate. C_DecryptDigestUpdate returns exactly 16 bytes of plaintext, since at this point, Cryptoki doesn't know if there's more ciphertext coming, or if the last block of ciphertext held any padding. These 16 bytes of plaintext are passed into the active digesting operation.

Since there is no more ciphertext, the application calls C_DecryptFinal. This tells Cryptoki that there's no more ciphertext coming, and the call returns the last 2 bytes of plaintext. However, since the active decryption and digesting operations are linked only through the C_DecryptDigestUpdate call, these 2 bytes of plaintext are not passed on to be digested.

A call to C_DigestFinal, therefore, would compute the message digest of the first 16 bytes of the plaintext, not the message digest of the entire plaintext. It is crucial that, before C_DigestFinal is called, the last 2 bytes of plaintext get passed into the active digesting operation.

Because of this, it is critical that when an application uses a padded decryption mechanism with C_DecryptDigestUpdate, it knows exactly how much plaintext has been passed into the active digesting operation. Extreme caution is warranted when using a padded decryption mechanism with C_DecryptDigestUpdate.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define BUF_SZ 512
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_BYTE iv[8];
CK_MECHANISM decryptionMechanism = {
CKM_DES_ECB, iv, sizeof(iv)
};
CK_MECHANISM digestMechanism = {
CKM_MD5, NULL_PTR, 0
};
CK_BYTE encryptedData[(2*BUF_SZ)+8];
CK_BYTE digest[16];
CK_ULONG ulDigestLen;
CK_BYTE data[BUF_SZ];
CK_ULONG ulDataLen, ulLastUpdateSize;
CK_RV rv;
.
.
.
memset(iv, 0, sizeof(iv));
memset(encryptedData, 'A', ((2*BUF_SZ)+8));
rv = C_DecryptInit(hSession, &decryptionMechanism, hKey);
if (rv != CKR_OK) {
.
.
.
}
rv = C_DigestInit(hSession, &digestMechanism);
if (rv != CKR_OK){
.
.
.
}
ulDataLen = sizeof(data);
rv = C_DecryptDigestUpdate(
hSession,
&encryptedData[0], BUF_SZ,
data, &ulDataLen);
.
.
.
ulDataLen = sizeof(data);
rv = C_DecryptDigestUpdate(
hSession,
&encryptedData[BUF_SZ], BUF_SZ,
data, &uldataLen);
.
.
.
/*
* The last portion of the buffer needs to be handled with 
* separate calls to deal with padding issues in ECB mode
*/
/* First, complete the decryption of the buffer */
ulLastUpdateSize = sizeof(data);
rv = C_DecryptUpdate(
hSession,
&encryptedData[BUF_SZ*2], 8,
data, &ulLastUpdateSize);
.
.
.
/* Get last piece of plaintext (should have length 0, here) */
ulDataLen = sizeof(data)-ulLastUpdateSize;
rv = C_DecryptFinal(hSession, &data[ulLastUpdateSize], &ulDataLen);
if (rv != CKR_OK) {
.
.
.
}
/* Digest last bit of plaintext */
rv = C_DigestUpdate(hSession, &data[BUF_SZ*2], 5);
if (rv != CKR_OK) {
.
.
.
}
ulDigestLen = sizeof(digest);
rv = C_DigestFinal(hSession, digest, &ulDigestLen);
if (rv != CKR_OK) {
.
.
.
}

C_SignEncryptUpdate

CK_RV C_SignEncryptUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pPart,
CK_ULONG ulPartLen,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG_PTR pulEncryptedPartLen
);

C_SignEncryptUpdate continues a multiple-part combined signature and encryption operation, processing another data part.

Parameters:
hSession is the session's handle;
pPart points to the data part; usPartLen is the length of the data part;
pEncryptedPart points to the location that receives the digested and encrypted data part; pusEncryptedPart points to the location that holds the length of the encrypted data part.
C_SignEncryptUpdate uses the convention described in Section on producing output.

Signature and encryption operations must both be active (they must have been initialized with C_SigntInit and C_EncryptInit, respectively). This function may be called any number of times in succession, and may be interspersed with C_SignUpdate and C_EncryptUpdate calls.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define BUF_SZ 512
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hEncryptionKey, hMacKey;
CK_BYTE iv[8];
CK_MECHANISM signMechanism = {
CKM_DES_MAC, NULL_PTR, 0
};
CK_MECHANISM encryptionMechanism = {
CKM_DES_ECB, iv, sizeof(iv)
};
CK_BYTE encryptedData[BUF_SZ];
CK_ULONG ulEncryptedDataLen;
CK_BYTE MAC[4];
CK_ULONG ulMacLen;
CK_BYTE data[(2*BUF_SZ)+8];
CK_RV rv;
int i;
.
.
.
memset(iv, 0, sizeof(iv));
memset(data, 'A', ((2*BUF_SZ)+5));
rv = C_EncryptInit(hSession, &encryptionMechanism, hEncryptionKey);
if (rv != CKR_OK) {
.
.
.
}
rv = C_SignInit(hSession, &signMechanism, hMacKey);
if (rv != CKR_OK) {
.
.
.
}
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_SignEncryptUpdate(
hSession,
&data[0], BUF_SZ,
encryptedData, &ulEncryptedDataLen);
.
.
.
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_SignEncryptUpdate(
hSession,
&data[BUF_SZ], BUF_SZ,
encryptedData, &ulEncryptedDataLen);
.
.
.
/*
* The last portion of the buffer needs to be handled with 
* separate calls to deal with padding issues in ECB mode
*/
/* First, complete the signature on the buffer */
rv = C_SignUpdate(hSession, &data[BUF_SZ*2], 5);
.
.
.
ulMacLen = sizeof(MAC);
rv = C_DigestFinal(hSession, MAC, &ulMacLen);
.
.
.
/* Then pad last part with 3 0x00 bytes, and complete encryption */
for(i=0;i<3;i++)
data[((BUF_SZ*2)+5)+i] = 0x00;
/* Now, get second-to-last piece of ciphertext */
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_EncryptUpdate(
hSession,
&data[BUF_SZ*2], 8,
encryptedData, &ulEncryptedDataLen);
.
.
.
/* Get last piece of ciphertext (should have length 0, here) */
ulEncryptedDataLen = sizeof(encryptedData);
rv = C_EncryptFinal(hSession, encryptedData, &ulEncryptedDataLen);
.
.
.

C_DecryptVerifyUpdate

CK_RV C_DecryptVerifyUpdate(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pEncryptedPart,
CK_ULONG ulEncryptedPartLen,
CK_BYTE_PTR pPart,
CK_ULONG_PTR pulPartLen
);

C_DecryptVerifyUpdate continues a multiple-part combined decryption and verification operation, processing another data part.

Parameters:
hSession is the session's handle;
pEncryptedData points to the encrypted data;
ulEncryptedDataLen is the length of the encrypted data;
pData points to the location that receives the recovered data;
pulDataLen points to the location that holds the length of the recovered data.
C_DecryptVerifyUpdate uses the convention described in Section on producing output.

Decryption and signature operations must both be active (they must have been initialized with C_DecryptInit and C_VerifyInit, respectively). This function may be called any number of times in succession, and may be interspersed with C_DecryptUpdate and C_VerifyUpdate calls.

Use of C_DecryptVerifyUpdate involves a pipelining issue that does not arise when using C_SignEncryptUpdate, the "inverse function" of C_DecryptVerifyUpdate. This is because when C_SignEncryptUpdate is called, precisely the same input is passed to both the active signing operation and the active encryption operation; however, when C_DecryptVerifyUpdate is called, the input passed to the active verifying operation is the output of the active decryption operation. This issue comes up only when the mechanism used for decryption performs padding.

In particular, envision a 24-byte ciphertext which was obtained by encrypting an 18-byte plaintext with DES in CBC mode with PKCS padding. Consider an application which will simultaneously decrypt this ciphertext and verify a signature on the original plaintext thereby obtained.

After initializing decryption and verification operations, the application passes the 24-byte ciphertext (3 DES blocks) into C_DecryptVerifyUpdate. C_DecryptVerifyUpdate returns exactly 16 bytes of plaintext, since at this point, Cryptoki doesn't know if there's more ciphertext coming, or if the last block of ciphertext held any padding. These 16 bytes of plaintext are passed into the active verification operation.

Since there is no more ciphertext, the application calls C_DecryptFinal. This tells Cryptoki that there's no more ciphertext coming, and the call returns the last 2 bytes of plaintext. However, since the active decryption and verification operations are linked only through the C_DecryptVerifyUpdate call, these 2 bytes of plaintext are not passed on to the verification mechanism.

A call to C_VerifyFinal, therefore, would verify whether or not the signature supplied is a valid signature on the first 16 bytes of the plaintext, not on the entire plaintext. It is crucial that, before C_VerifyFinal is called, the last 2 bytes of plaintext get passed into the active verification operation.

Because of this, it is critical that when an application uses a padded decryption mechanism with C_DecryptVerifyUpdate, it knows exactly how much plaintext has been passed into the active verification operation. Extreme caution is warranted when using a padded decryption mechanism with C_DecryptVerifyUpdate.

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

#define BUF_SZ 512
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hDecryptionKey, hMacKey;
CK_BYTE iv[8];
CK_MECHANISM decryptionMechanism = {
CKM_DES_ECB, iv, sizeof(iv)
};
CK_MECHANISM verifyMechanism = {
CKM_DES_MAC, NULL_PTR, 0
};
CK_BYTE encryptedData[(2*BUF_SZ)+8];
CK_BYTE MAC[4];
CK_ULONG ulMacLen;
CK_BYTE data[BUF_SZ];
CK_ULONG ulDataLen, ulLastUpdateSize;
CK_RV rv;
.
.
.
memset(iv, 0, sizeof(iv));
memset(encryptedData, 'A', ((2*BUF_SZ)+8));
rv = C_DecryptInit(hSession, &decryptionMechanism, hDecryptionKey);
if (rv != CKR_OK) {
.
.
.
}
rv = C_VerifyInit(hSession, &verifyMechanism, hMacKey);
if (rv != CKR_OK){
.
.
.
}
ulDataLen = sizeof(data);
rv = C_DecryptVerifyUpdate(
hSession,
&encryptedData[0], BUF_SZ,
data, &ulDataLen);
.
.
.
ulDataLen = sizeof(data);
rv = C_DecryptVerifyUpdate(
hSession,
&encryptedData[BUF_SZ], BUF_SZ,
data, &uldataLen);
.
.
.
/*
* The last portion of the buffer needs to be handled with 
* separate calls to deal with padding issues in ECB mode
*/
/* First, complete the decryption of the buffer */
ulLastUpdateSize = sizeof(data);
rv = C_DecryptUpdate(
hSession,
&encryptedData[BUF_SZ*2], 8,
data, &ulLastUpdateSize);
.
.
.
/* Get last little piece of plaintext. Should have length 0 */
ulDataLen = sizeof(data)-ulLastUpdateSize;
rv = C_DecryptFinal(hSession, &data[ulLastUpdateSize], &ulDataLen);
if (rv != CKR_OK) {
.
.
.
}
/* Send last bit of plaintext to verification operation */
rv = C_VerifyUpdate(hSession, &data[BUF_SZ*2], 5);
if (rv != CKR_OK) {
.
.
.
}
rv = C_VerifyFinal(hSession, MAC, ulMacLen);
if (rv == CKR_SIGNATURE_INVALID) {
.
.
.
}

Key management functions

Cryptoki provides the following functions for key management. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_GenerateKey

CK_RV C_GenerateKey(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulCount,
CK_OBJECT_HANDLE_PTR phKey
);

C_GenerateKey generates a secret key, creating a new key object.

Parameters:
hSession is the session's handle;
pMechanism points to the key generation mechanism;
pTemplate points to the template for the new key;
ulCount is the number of attributes in the template;
phKey points to the location that receives the handle of the new key.
Since the type of key to be generated is implicit in the key generation mechanism, the template does not need to supply a key type. If it does supply a key type which is inconsistent with the key generation mechanism, C_GenerateKey fails and returns the error code CKR_TEMPLATE_INCONSISTENT.

The key object created by a successful call to C_GenerateKey will have its CKA_LOCAL attribute set to TRUE.

Returns:
CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;
CK_MECHANISM mechanism = {
CKM_DES_KEY_GEN, NULL_PTR, 0
};
CK_RV rv;
.
.
.
rv = C_GenerateKey(hSession, &mechanism, NULL_PTR, 0, &hKey);
if (rv == CKR_OK) {
.
.
.
}

C_GenerateKeyPair

CK_RV C_GenerateKeyPair(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_ATTRIBUTE_PTR pPublicKeyTemplate,
CK_ULONG ulPublicKeyAttributeCount,
CK_ATTRIBUTE_PTR pPrivateKeyTemplate,
CK_ULONG ulPrivateKeyAttributeCount,
CK_OBJECT_HANDLE_PTR phPublicKey,
CK_OBJECT_HANDLE_PTR phPrivateKey
);

C_GenerateKeyPair generates a public/private key pair, creating new key objects.

Parameters:
hSession is the session's handle;
pMechanism points to the key generation mechanism;
pPublicKeyTemplate points to the template for the public key;
ulPublicKeyAttributeCount is the number of attributes in the public-key template;
pPrivateKeyTemplate points to the template for the private key;
ulPrivateKeyAttributeCount is the number of attributes in the private-key template;
phPublicKey points to the location that receives the handle of the new public key;
phPrivateKey points to the location that receives the handle of the new private key.
Since the types of keys to be generated are implicit in the key pair generation mechanism, the templates do not need to supply key types. If one of the templates does supply a key type which is inconsistent with the key generation mechanism, C_GenerateKeyPair fails and returns the error code CKR_TEMPLATE_INCONSISTENT.

The key objects created by a successful call to C_GenerateKeyPair will have their CKA_LOCAL attributes set to TRUE.

Returns:
CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hPublicKey, hPrivateKey;
CK_MECHANISM mechanism = {
CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0
};
CK_ULONG modulusBits = 768;
CK_BYTE publicExponent[] = { 3 };
CK_BYTE subject[] = {...};
CK_BYTE id[] = {123};
CK_BBOOL true = TRUE;
CK_ATTRIBUTE publicKeyTemplate[] = {
{CKA_ENCRYPT, &true, sizeof(true)},
{CKA_VERIFY, &true, sizeof(true)},
{CKA_WRAP, &true, sizeof(true)},
{CKA_MODULUS_BITS, &modulusBits, sizeof(modulusBits)},
{CKA_PUBLIC_EXPONENT, publicExponent, sizeof (publicExponent)}
};
CK_ATTRIBUTE privateKeyTemplate[] = {
{CKA_TOKEN, &true, sizeof(true)},
{CKA_PRIVATE, &true, sizeof(true)},
{CKA_SUBJECT, subject, sizeof(subject)},
{CKA_ID, id, sizeof(id)},
{CKA_SENSITIVE, &true, sizeof(true)},
{CKA_DECRYPT, &true, sizeof(true)},
{CKA_SIGN, &true, sizeof(true)},
{CKA_UNWRAP, &true, sizeof(true)}
};
CK_RV rv;
rv = C_GenerateKeyPair(
hSession, &mechanism,
publicKeyTemplate, 5,
privateKeyTemplate, 8,
&hPublicKey, &hPrivateKey);
if (rv == CKR_OK) {
.
.
.
}

C_WrapKey

CK_RV C_WrapKey(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hWrappingKey,
CK_OBJECT_HANDLE hKey,
CK_BYTE_PTR pWrappedKey,
CK_ULONG_PTR pulWrappedKeyLen
);

C_WrapKey wraps (i.e., encrypts) a private or secret key.

Parameters:
hSession is the session's handle;
pMechanism points to the wrapping mechanism;
hWrappingKey is the handle of the wrapping key; hKey is the handle of the key to be wrapped;
pWrappedKey points to the location that receives the wrapped key; and pulWrappedKeyLen points to the location that receives the length of the wrapped key.
C_WrapKey uses the convention described in Section on producing output.

The CKA_WRAP attribute of the wrapping key, which indicates whether the key supports wrapping, must be TRUE. The CKA_EXTRACTABLE attribute of the key to be wrapped must also be TRUE.

If the key to be wrapped cannot be wrapped for some token-specific reason, despite its having its CKA_EXTRACTABLE attribute set to TRUE, then C_WrapKey fails with error code CKR_KEY_NOT_WRAPPABLE. If it cannot be wrapped with the specified wrapping key and mechanism solely because of its length, then C_WrapKey fails with error code CKR_KEY_SIZE_RANGE.

C_WrapKey can a priori be used in the following situations:

Returns:
CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_HANDLE_INVALID, CKR_KEY_NOT_WRAPPABLE, CKR_KEY_SIZE_RANGE, CKR_KEY_UNEXTRACTABLE, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPING_KEY_HANDLE_INVALID, CKR_WRAPPING_KEY_SIZE_RANGE, CKR_WRAPPING_KEY_TYPE_INCONSISTENT.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hWrappingKey, hKey;
CK_MECHANISM mechanism = {
CKM_DES3_ECB, NULL_PTR, 0
};
CK_BYTE wrappedKey[8];
CK_ULONG ulWrappedKeyLen;
CK_RV rv;
.
.
.
ulWrappedKeyLen = sizeof(wrappedKey);
rv = C_WrapKey(
hSession, &mechanism,
hWrappingKey, hKey,
wrappedKey, &ulWrappedKeyLen);
if (rv == CKR_OK) {
.
.
.
}

C_UnwrapKey

CK_RV C_UnwrapKey(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hUnwrappingKey,
CK_BYTE_PTR pWrappedKey,
CK_ULONG ulWrappedKeyLen,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulAttributeCount,
CK_OBJECT_HANDLE_PTR phKey
);

C_UnwrapKey unwraps (i.e. decrypts) a wrapped key, creating a new private key or secret key object.

Parameters:
hSession is the session's handle;
pMechanism points to the unwrapping mechanism;
hUnwrappingKey is the handle of the unwrapping key; pWrappedKey points to the wrapped key;
ulWrappedKeyLen is the length of the wrapped key;
pTemplate points to the template for the new key;
ulAttributeCount is the number of attributes in the template;
phKey points to the location that receives the handle of the recovered key.
The CKA_UNWRAP attribute of the unwrapping key, which indicates whether the key supports unwrapping, must be TRUE.

The new key will have the CKA_ALWAYS_SENSITIVE attribute set to FALSE, and the CKA_EXTRACTABLE attribute set to TRUE. If the template for the new key has the CKA_EXTRACTABLE attribute set to FALSE, C_UnwrapKey fails with the error CKR_TEMPLATE_INCONSISTENT.

When C_UnwrapKey is used to unwrap a key with the CKM_KEY_WRAP_SET_OAEP mechanism (see Section), additional "extra data" is decrypted at the same time that the key is unwrapped. The return of this data follows the convention in Section on producing output. If the extra data is not returned from a call to C_UnwrapKey (either because the call was only to find out how large the extra data is, or because the buffer provided for the extra data was too small), then C_UnwrapKey will not create a new key, either.

The key object created by a successful call to C_UnwrapKey will have its CKA_LOCAL attribute set to FALSE.

Returns:
CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_UNWRAPPING_KEY_HANDLE_INVALID, CKR_UNWRAPPING_KEY_SIZE_RANGE, CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPED_KEY_INVALID, CKR_WRAPPED_KEY_LEN_RANGE.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hUnwrappingKey, hKey;
CK_MECHANISM mechanism = {
CKM_DES3_ECB, NULL_PTR, 0
};
CK_BYTE wrappedKey[8] = {...};
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_DES;
CK_BBOOL true = TRUE;
CK_ATTRIBUTE template[] = {
{CKA_CLASS, &keyClass, sizeof(keyClass)},
{CKA_KEY_TYPE, &keyType, sizeof(keyType)},
{CKA_ENCRYPT, &true, sizeof(true)},
{CKA_DECRYPT, &true, sizeof(true)}
};
CK_RV rv;
.
.
.
rv = C_UnwrapKey(
hSession, &mechanism, hUnwrappingKey,
wrappedKey, sizeof(wrappedKey), template, 4, &hKey);
if (rv == CKR_OK) {
.
.
.
}

C_DeriveKey

CK_RV C_DeriveKey(
CK_SESSION_HANDLE hSession,
CK_MECHANISM_PTR pMechanism,
CK_OBJECT_HANDLE hBaseKey,
CK_ATTRIBUTE_PTR pTemplate,
CK_ULONG ulAttributeCount,
CK_OBJECT_HANDLE_PTR phKey
);

C_DeriveKey derives a key from a base key, creating a new key object.

Parameters:
hSession is the session's handle;
pMechanism points to a structure that specifies the key derivation mechanism;
hBaseKey is the handle of the base key;
pTemplate points to the template for the new key;
ulAttributeCount is the number of attributes in the template;
phKey points to the location that receives the handle of the derived key.
The values of the CK_SENSITIVE, CK_ALWAYS_SENSITIVE, CK_EXTRACTABLE, and CK_NEVER_EXTRACTABLE attributes for the base key affect the values that these attributes can hold for the newly-derived key. See the description of each particular key-derivation mechanism in Section for any constraints of this type.

The key object created by a successful call to C_DeriveKey will have its CKA_LOCAL attribute set to FALSE.

Returns:
CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALUE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_KEY_HANDLE_INVALID, CKR_KEY_TYPE_INCONSISTENT, CKR_KEY_SIZE_RANGE, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OPERATION_ACTIVE, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hPublicKey, hPrivateKey, hKey;
CK_MECHANISM keyPairMechanism = {
CKM_DH_PKCS_KEY_PAIR_GEN, NULL_PTR, 0
};
CK_BYTE prime[] = {...};
CK_BYTE base[] = {...};
CK_BYTE publicValue[128];
CK_BYTE otherPublicValue[128];
CK_MECHANISM mechanism = {
CKM_DH_PKCS_DERIVE, otherPublicValue, sizeof(otherPublicValue)
};
CK_ATTRIBUTE pTemplate[] = {
CKA_VALUE, &publicValue, sizeof(publicValue)}
};
CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
CK_KEY_TYPE keyType = CKK_DES;
CK_BBOOL true = TRUE;
CK_ATTRIBUTE publicKeyTemplate[] = {
{CKA_PRIME, prime, sizeof(prime)},
{CKA_BASE, base, sizeof(base)}
};
CK_ATTRIBUTE privateKeyTemplate[] = {
{CKA_DERIVE, &true, sizeof(true)}
};
CK_ATTRIBUTE template[] = {
{CKA_CLASS, &keyClass, sizeof(keyClass)},
{CKA_KEY_TYPE, &keyType, sizeof(keyType)},
{CKA_ENCRYPT, &true, sizeof(true)},
{CKA_DECRYPT, &true, sizeof(true)}
};
CK_RV rv;
.
.
.
rv = C_GenerateKeyPair(
hSession, &keyPairMechanism,
publicKeyTemplate, 2,
privateKeyTemplate, 1,
&hPublicKey, &hPrivateKey);
if (rv == CKR_OK) {
rv = C_GetAttributeValue(hSession, hPublicKey, &pTemplate, 1);
if (rv == CKR_OK) {
/* Put other guy's public value in otherPublicValue */
.
.
.
rv = C_DeriveKey(
hSession, &mechanism,
hPrivateKey, template, 4, &hKey);
if (rv == CKR_OK) {
.
.
.
}
}
}

Random number generation functions

Cryptoki provides the following functions for generating random numbers. All these functions may run in parallel with the application if the session was opened with the CKF_SERIAL_SESSION flag set to FALSE (check the return code of the function call to see if the function is running in parallel).

C_SeedRandom

CK_RV C_SeedRandom(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pSeed,
CK_ULONG ulSeedLen
);

C_SeedRandom mixes additional seed material into the token's random number generator.

Parameters:
hSession is the session's handle;
pSeed points to the seed material; and ulSeedLen is the length in bytes of the seed material.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_ACTIVE, CKR_RANDOM_SEED_NOT_SUPPORTED, CKR_RANDOM_NO_RNG, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
The return code CKR_RANDOM_NO_RNG has a higher priority than the return code CKR_RANDOM_SEED_NOT_SUPPORTED. That is, if the token doesn't have a random number generator, then C_SeedRandom will return the value CKR_RANDOM_NO_RNG.

See also:
C_GenerateRandom.

C_GenerateRandom

CK_RV C_GenerateRandom(
CK_SESSION_HANDLE hSession,
CK_BYTE_PTR pRandomData,
CK_ULONG ulRandomLen
);

C_GenerateRandom generates random data.

Parameters:
hSession is the session's handle;
pRandomData points to the location that receives the random data; and ulRandomLen is the length in bytes of the random data to be generated.
Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_PARALLEL, CKR_OPERATION_ACTIVE, CKR_RANDOM_NO_RNG, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.
Example:

CK_SESSION_HANDLE hSession;
CK_BYTE seed[] = {...};
CK_BYTE randomData[] = {...};
CK_RV rv;
.
.
.
rv = C_SeedRandom(hSession, seed, sizeof(seed));
if (rv != CKR_OK) {
.
.
.
}
rv = C_GenerateRandom(hSession, randomData, sizeof(randomData));
if (rv == CKR_OK) {
.
.
.
}

Parallel function management functions

Cryptoki provides the following functions for managing parallel execution of cryptographic functions:

C_GetFunctionStatus

CK_RV C_GetFunctionStatus(
CK_SESSION_HANDLE hSession
);

C_GetFunctionStatus obtains the status of a function running in parallel with an application.

Parameters:
hSession is the session's handle.
If there is currently a function running in parallel in the specified session, C_GetFunctionStatus returns CK_FUNCTION_PARALLEL. If the most recently-executed Cryptoki function other than C_GetFunctionStatus that was called in the specified session was not executed in parallel (or if no Cryptoki function other than C_GetFunctionState has been called in the specified session), then C_GetFunctionStatus returns CK_FUNCTION_NOT_PARALLEL. Otherwise, C_GetFunctionState returns the return value of whatever the last parallel function executed in the specified session was.

Typically, an application might call this function repeatedly when a function is executing in parallel. Eventually, once the function has finished its execution, the return value of C_GetFunctionStatus will no longer be CKR_FUNCTION_PARALLEL; instead, it will be the return code of the function. Because of the way C_GetFunctionState 's behavior is defined above, repeated calls to C_GetFunctionStatus will all yield the same return code of the function (until some other Cryptoki function is called in the specified session).

Note that the application will also receive a CKN_COMPLETE notification callback when the function completes its parallel execution, assuming that the session the function is running in was opened with callbacks.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_NOT_PARALLEL, CKR_FUNCTION_PARALLEL, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
In addition to the return values listed above, once the function executing in parallel is finished executing, calls to C_GetFunctionStatus will return whatever the error return of the parallel function was.

See also:
C_CancelFunction.

C_CancelFunction

CK_RV C_CancelFunction(
CK_SESSION_HANDLE hSession
);

C_CancelFunction cancels a function running in parallel with an application.

Parameters:
hSession is the session's handle.
Note that C_CancelFunction cannot be used to cancel a function which is not running in parallel. For example, consider an application which consists of two threads, one of which is executing a (slow) C_GenerateKeyPair in session 1, which is a serial session. If the other thread attempts to cancel the C_GenerateKeyPair call with C_CancelFunction, the C_CancelFunction call may block until the C_GenerateKeyPair call is done, and then return the value CKR_FUNCTION_NOT_PARALLEL.

Returns:
CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_NOT_PARALLEL, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.
Example:

CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hPublicKey, hPrivateKey;
CK_MECHANISM mechanism = {
CKM_RSA_PKCS_KEY_PAIR_GEN, NULL_PTR, 0
};
CK_ULONG modulusBits = 768;
CK_BYTE publicExponent[] = {...};
CK_BYTE subject[] = {...};
CK_BYTE id[] = {123};
CK_BBOOL true = TRUE;
CK_ATTRIBUTE publicKeyTemplate[] = {
{CKA_ENCRYPT, &true, sizeof(true)},
{CKA_VERIFY, &true, sizeof(true)},
{CKA_WRAP, &true, sizeof(true)},
{CKA_MODULUS_BITS, &modulusBits, sizeof(modulusBits)},
{CKA_PUBLIC_EXPONENT, publicExponent, sizeof(publicExponent)}
};
CK_ATTRIBUTE privateKeyTemplate[] = {
{CKA_TOKEN, &true, sizeof(true)},
{CKA_PRIVATE, &true, sizeof(true)},
{CKA_SUBJECT, subject, sizeof(subject)},
{CKA_ID, id, sizeof(id)},
{CKA_SENSITIVE, &true, sizeof(true)},
{CKA_DECRYPT, &true, sizeof(true)},
{CKA_SIGN, &true, sizeof(true)},
{CKA_UNWRAP, &true, sizeof(true)}
};
CK_RV rv;
.
.
.
rv = C_GenerateKeyPair(
hSession, &mechanism,
publicKeyTemplate, 5,
privateKeyTemplate, 8,
&hPublicKey, &hPrivateKey);
while (rv == CKR_FUNCTION_PARALLEL) {
/* Check if user wants to cancel function */
if (kbhit()) {
if (getch() == 27) { /* If user hit ESCape key */
rv = C_CancelFunction(hSession);
.
.
.
}
}
/* Perform other tasks or delay */
.
.
.
rv = C_GetFunctionStatus(hSession);
}

Callback functions

Cryptoki uses function pointers of type CK_NOTIFY to notify the application of certain events. There are four different types of application callbacks.

Token insertion callbacks

An application can use C_OpenSession to set up a token insertion callback function (assuming insertion callbacks are supported for that slot). When a token is inserted into the specified slot, the application callback function that was supplied to C_OpenSession is called with the arguments (0, CKN_TOKEN_INSERTION, pApplication), where pApplication was supplied to C_OpenSession. Token insertion callbacks should return the value CKR_OK.

Token removal callbacks

When a token is removed from its slot, each open session which had a callback function specified when it was opened receives a callback. Each session's callback is called with the arguments (hSession, CKN_DEVICE_REMOVED, pApplication), where hSession is the session's handle (although when the callback occurs, the session has just been closed because of the token removal) and pApplication was supplied to C_OpenSession. It is not necessarily the case that all slots/tokens will support token removal callbacks. Token removal callbacks should return the value CKR_OK.

Parallel function completion callbacks

When a function executing in parallel finishes execution, the callback for the session that function was running in (if there is such a callback) is executed with arguments (hSession, CKN_COMPLETE, pApplication), where hSession is the session's handle and pApplication was supplied to C_OpenSession. Parallel function completion callbacks should return the value CKR_OK.

Serial function surrender callbacks

Functions executing in serial sessions can periodically surrender control to the application who called them, if the session they are executing in has a callback function. They do this by calling their session's callback with arguments (hSession, CKN_SURRENDER, pApplication), where hSession is the session's handle and pApplication was supplied to C_OpenSession. Serial function surrender callbacks should return either the value CKR_OK (to indicate that Cryptoki should continue executing the function) or the value CKR_CANCEL (to indicate that Cryptoki should abort execution of the function). Of course, before returning one of these values, the callback function can perform some computation.

Note that this type of callback is somewhat different from the other three types of callbacks, because it doesn't require a spontaneous generation of a thread or process to execute the callback.


RSA Security Inc. Public-Key Cryptography Standards - PKCS#11 - v200