![]() | Cryptographic Token Interface Standard |
PKCS#11 |
Function return values
Universal Cryptoki function return values
Any Cryptoki function can return any of the following values:
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:
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:
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.
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:
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.
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.
pReserved | is reserved for future versions: for this version, it should be set to NULL_PTR. |
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.
pReserved | is reserved for future versions: for this version, it should be set to NULL_PTR. |
C_GetInfo returns general information about Cryptoki.
pInfo | points to the location that receives the information. |
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);
CK_RV C_GetFunctionList( CK_FUNCTION_LIST_PTR_PTR ppFunctionList );
C_GetFunctionList obtains a pointer to the Cryptoki library's list of function pointers.
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. |
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.
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.
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. |
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);
CK_RV C_GetSlotInfo( CK_SLOT_ID slotID, CK_SLOT_INFO_PTR pInfo );
C_GetSlotInfo obtains information about a particular slot in the system.
slotID | is the ID of the slot; |
pInfo | points to the location that receives the slot information. |
CK_RV C_GetTokenInfo( CK_SLOT_ID slotID, CK_TOKEN_INFO_PTR pInfo );
C_GetTokenInfo obtains information about a particular token in the system.
slotID | is the ID of the token's slot; |
pInfo | points to the location that receives the token information. |
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); }
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.
SlotID | is the ID of the token's slot; |
pulCount | points to the location that receives the number of mechanisms. |
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); }
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.
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. |
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) { . . . } }
CK_RV C_InitToken( CK_SLOT_ID slotID, CK_CHAR_PTR pPin, CK_ULONG ulPinLen, CK_CHAR_PTR pLabel );
C_InitToken initializes a token.
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). |
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.
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) { . . . }
CK_RV C_InitPIN( CK_SESSION_HANDLE hSession, CK_CHAR_PTR pPin, CK_ULONG ulPinLen );
C_InitPIN initializes the normal user's PIN.
hSession | is the session's handle; |
pPin | points to the normal user's PIN; ulPinLen is the length in bytes of the PIN. |
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.
CK_SESSION_HANDLE hSession; CK_CHAR newPin[]= {"NewPIN"}; CK_RV rv; rv = C_InitPIN(hSession, newPin, sizeof(newPin)); if (rv == CKR_OK) { . . . }
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.
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. |
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.
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:
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.
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.
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. |
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.
CK_RV C_CloseSession( CK_SESSION_HANDLE hSession );
C_CloseSession closes a session between an application and a token.
hSession | is the session's handle. |
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.
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); }
CK_RV C_CloseAllSessions( CK_SLOT_ID slotID );
C_CloseAllSessions closes all sessions an application has with a token.
slotID | specifies the token's slot. |
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).
CK_SLOT_ID slotID; CK_RV rv; . . . rv = C_CloseAllSessions(slotID);
CK_RV C_GetSessionInfo( CK_SESSION_HANDLE hSession, CK_SESSION_INFO_PTR pInfo );
C_GetSessionInfo obtains information about a session.
hSession | is the session's handle; |
pInfo | points to the location that receives the session information. |
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) { . . . } . . . }
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.
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. |
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.
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.
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). |
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).
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 */ . . . }
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.
hSession | is a session handle; |
userType | is the user type; |
pPin | points to the user's PIN; ulPinLen is the length of the PIN. |
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.
CK_RV C_Logout( CK_SESSION_HANDLE hSession );
C_Logout logs a user out from a token.
hSession | is the session's handle. |
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.
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 .
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.
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. |
Only session object can be created during a read-only session. Only public objects can be created unless the normal user is logged in.
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) { . . . }
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.
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. |
Only session objects can be created during a read-only session. Only public objects can be created unless the normal user is logged in.
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, ©Template, 1, &hNewKey); . . . }
CK_RV C_DestroyObject( CK_SESSION_HANDLE hSession, CK_OBJECT_HANDLE hObject );
C_DestroyObject destroys an object.
hSession | is the session's handle; |
hObject | is the object's handle. |
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.
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. |
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); . . . }
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.
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. |
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); }
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.
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. |
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.
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) { . . . }
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.
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. |
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.
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.
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. |
The search must have been initialized with C_FindObjectsInit.
CK_RV C_FindObjectsFinal( CK_SESSION_HANDLE hSession );
C_FindObjectsFinal terminates a search for token and session objects.
hSession | is the session's handle. |
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).
CK_RV C_EncryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey );
C_EncryptInit initializes an encryption operation.
hSession | is the session's handle; |
pMechanism | points to the encryption mechanism; |
hKey | is the handle of the encryption key. |
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.
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.
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. |
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.
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.
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. |
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.
CK_RV C_EncryptFinal( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastEncryptedPart, CK_ULONG_PTR pulLastEncryptedPartLen );
C_EncryptFinal finishes a multiple-part encryption operation.
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. |
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.
#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).
CK_RV C_DecryptInit( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism, CK_OBJECT_HANDLE hKey );
C_DecryptInit initializes a decryption operation.
hSession | is the session's handle; |
pMechanism | points to the decryption mechanism; |
hKey | is the handle of the decryption key. |
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
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.
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. |
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.
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.
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. |
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.
CK_RV C_DecryptFinal( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pLastPart, CK_ULONG_PTR pulLastPartLen );
C_DecryptFinal finishes a multiple-part decryption operation.
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. |
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.
#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).
CK_RV C_DigestInit( CK_SESSION_HANDLE hSession, CK_MECHANISM_PTR pMechanism );
C_DigestInit initializes a message-digesting operation.
hSession | is the session's handle; |
pMechanism | points to the digesting mechanism. |
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.
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. |
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.
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.
hSession | is the session's handle, pPart points to the data part; |
ulPartLen | is the length of the data part. |
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.
hSession | is the session's handle; |
hKey | is the handle of the secret key to be digested. |
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.
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.
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. |
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.
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).
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.
hSession | is the session's handle; |
pMechanism | points to the signature mechanism; |
hKey | is the handle of the signature key. |
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.
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.
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. |
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.
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.
hSession | is the session's handle, pPart points to the data part; |
ulPartLen | is the length of the data part. |
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.
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. |
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.
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); . . . }
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.
hSession | is the session's handle; |
pMechanism | points to the structure that specifies the signature mechanism; |
hKey | is the handle of the signature key. |
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.
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.
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. |
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.
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).
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.
hSession | is the session's handle; |
pMechanism | points to the structure that specifies the verification mechanism; |
hKey | is the handle of the verification key. |
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.
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.
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. |
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.
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.
hSession | is the session's handle, pPart points to the data part; |
ulPartLen | is the length of the data part. |
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.
hSession | is the session's handle; |
pSignature | points to the signature; |
ulSignatureLen | is the length of the signature. |
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.
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)); . . . }
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.
hSession | is the session's handle; |
pMechanism | points to the structure that specifies the verification mechanism; |
hKey | is the handle of the verification key. |
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.
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.
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. |
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.
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).
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.
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. |
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).
#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); . . .
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.
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. |
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.
#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) { . . . }
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.
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. |
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.
#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); . . .
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.
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. |
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.
#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).
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.
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. |
The key object created by a successful call to C_GenerateKey will have its CKA_LOCAL attribute set to TRUE.
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) { . . . }
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.
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. |
The key objects created by a successful call to C_GenerateKeyPair will have their CKA_LOCAL attributes set to TRUE.
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) { . . . }
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.
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. |
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:
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) { . . . }
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.
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 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.
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) { . . . }
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.
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 key object created by a successful call to C_DeriveKey will have its CKA_LOCAL attribute set to FALSE.
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).
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.
hSession | is the session's handle; |
pSeed | points to the seed material; and ulSeedLen is the length in bytes of the seed material. |
CK_RV C_GenerateRandom( CK_SESSION_HANDLE hSession, CK_BYTE_PTR pRandomData, CK_ULONG ulRandomLen );
C_GenerateRandom generates random data.
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. |
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:
CK_RV C_GetFunctionStatus( CK_SESSION_HANDLE hSession );
C_GetFunctionStatus obtains the status of a function running in parallel with an application.
hSession | is the session's handle. |
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.
CK_RV C_CancelFunction( CK_SESSION_HANDLE hSession );
C_CancelFunction cancels a function running in parallel with an application.
hSession | is the session's handle. |
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.