IBM Cloud Docs
Cryptographic operations: GREP11 API

Cryptographic operations: GREP11 API

IBM Cloud® Hyper Protect Crypto Services provides a set of cryptography functions that are executed in a Hardware Security Module (HSM)A physical appliance that provides on-demand encryption, key management, and key storage as a managed service. in the cloud. You can perform cryptographic operations by remotely accessing these functions with the Enterprise PKCS #11 (EP11) over gRPC API calls (also referred to as GREP11).

For more information about how the GREP11 functions are related to PKCS #11 and EP11, see GREP11 introduction.

The GREP11 API can process up to 500 requests/second for a single crypto unit.

Accessing the API

A GREP11 API endpoint, a service ID API key, an IAM endpoint are needed for initialization before you perform any GREP11 API function calls. For more information, see Generating a GREP11 API request.

Error handling

GREP11 relies on the gRPC specification for error handling. When an error occurs, gRPC clients receive a message Status protocol buffer.

message Status {
    int32 code = 1;
    string message = 2;
    repeated google.protobuf.Any details = 3;
}

In the error message,

  • code includes the status code, which needs to be an enumerated-type (enum) value of the google.rpc.Code field.
  • message includes a developer-facing error message in English. Any user-facing error message needs to be localized and sent in the google.rpc.Status.details field, or localized by the user.
  • details lists messages that carry the error details. A common set of message types is available for the API to use.

GREP11 uses the Detail field to attach extra error code information.

message Grep11Error {
    uint64 Code = 1;
    string Detail = 2;
    bool Retry = 3;
}

The Code field can be cast to the CK_RV value in PKCS #11. This field contains the error codes that are defined by the PKCS #11 specification or the vendor extensions that are defined by EP11. EP11 uses only a subset of return values that PKCS #11 defines. For more information, see the 10.1.6 Return values section in Enterprise PKCS #11 Library structure.

An example in Golang that deals with errors is available.

GREP11 function list

PKCS #11 functions that are marked with an asterisk (*) in the table are implemented by EP11 over gRPC. Others are not implemented.

Table 1. Describes the implemented functions in EP11 over gRPC
PKCS #11 Enterprise PKCS #11 Enterprise PKCS #11 over gRPC Description
C_Initialize N/A N/A Initializes Cryptoki.
C_Finalize N/A N/A Clean up miscellaneous Cryptoki-associated resources.
C_GetInfo N/A N/A Obtains general information about Cryptoki.
C_GetFunctionList N/A N/A Obtains entry points of Cryptoki library functions.
C_GetSlotList N/A N/A Obtains a list of slots in the system.
C_GetSlotInfo N/A N/A Obtains information about a particular slot.
C_GetTokenInfo N/A N/A Obtains information about a particular token.
C_WaitForSlotEvent N/A N/A Waits for a slot event (token insertion, removal, and so on) to occur.
C_GetMechanismList* m_GetMechanismList GetMechanismList Obtains a list of mechanisms that are supported by a token.
C_GetMechanismInfo* m_GetMechanismInfo GetMechanismInfo Obtains information about a particular mechanism.
C_InitToken N/A N/A Initializes a token.
C_InitPIN N/A N/A Initializes the normal user’s PIN.
C_SetPIN N/A N/A Modifies the PIN of the current user.
C_OpenSession N/A N/A Opens a connection between an application and a particular token or sets up an application callback for token insertion.
C_CloseSession N/A N/A Closes a session.
C_CloseAllSessions N/A N/A Closes all sessions with a token.
C_GetSessionInfo N/A N/A Obtains information about the session.
C_GetOperationState N/A N/A Obtains the cryptographic operations state of a session.
C_SetOperationState N/A N/A Sets the cryptographic operations state of a session.
C_Login N/A N/A Logs in to a token.
C_Logout N/A N/A Logs out from a token.
C_CreateObject N/A N/A Creates an object.
C_CopyObject N/A N/A Creates a copy of an object.
C_DestroyObject N/A N/A Destroys an object.
C_GetObjectSize N/A N/A Obtains the size of an object in bytes.
C_GetAttributeValue* m_GetAttributeValue GetAttributeValue Obtains an attribute value of an object.
C_SetAttributeValue* m_SetAttributeValue SetAttributeValue Modifies an attribute value of an object. Only Boolean attributes can be modified.
C_FindObjectsInit N/A N/A Initializes an object search operation.
C_FindObjects N/A N/A Continues an object search operation.
C_FindObjectsFinal N/A N/A Finishes an object search operation.
C_EncryptInit* m_EncryptInit EncryptInit Initializes an encryption operation.
C_Encrypt* m_Encrypt Encrypt Encrypts single-part data.
C_EncryptUpdate* m_EncryptUpdate EncryptUpdate Continues a multiple-part encryption operation.
C_EncryptFinal* m_EncryptFinal EncryptFinal Finishes a multiple-part encryption operation.
N/A m_EncryptSingle EncryptSingle IBM extension, non-standard variant of Encrypt. Processes data in one pass, with one call. Does not return any state to host other than encrypted data.
N/A m_ReencryptSingle ReencryptSingle IBM extension, non-standard variant of Encrypt. Decrypts data with the original key and encrypts the raw data with a different key in a single call within the cloud HSM. Does not return any state to host other than the reencrypted data.
C_DecryptInit* m_DecryptInit DecryptInit Initializes a decryption operation.
C_Decrypt* m_Decrypt Decrypt Decrypts single-part encrypted data.
C_DecryptUpdate* m_DecryptUpdate DecryptUpdate Continues a multiple-part decryption operation.
C_DecryptFinal* m_DecryptFinal DecryptFinal Finishes a multiple-part decryption operation.
N/A m_DecryptSingle DecryptSingle IBM extension, non-standard variant of Decrypt. Processes data in one pass, with one call. Does not return any state to host other than decrypted data.
C_DigestInit* m_DigestInit DigestInit Initializes a message-digesting operation.
C_Digest* m_Digest Digest Digests single-part data. The length of the input data cannot be zero and the pointer that points to the input data location cannot be NULL.
C_DigestUpdate* m_DigestUpdate DigestUpdate Continues a multiple-part digesting operation. The length of the input data cannot be zero and the pointer that points to the input data location cannot be NULL.
C_DigestKey N/A N/A Digests a key.
C_DigestFinal* m_DigestFinal DigestFinal Finishes a multiple-part digesting operation.
N/A m_DigestSingle DigestSingle IBM extension, nonstandard extension, combination of DigestInit and Digest. Digests data in one pass, with one call, without constructing an intermediate digest state, and unnecessary roundtrips
C_SignInit* m_SignInit SignInit Initializes a signature operation.
C_Sign* m_Sign Sign Signs single-part data.
C_SignUpdate* m_SignUpdate SignUpdate Continues a multiple-part signature operation.
C_SignFinal* m_SignFinal SignFinal Finishes a multiple-part signature operation.
C_SignRecoverInit N/A N/A Initializes a signature operation, where the data is recovered from the signature.
C_SignRecover N/A N/A Signs single-part data, where the data is recovered from the signature.
N/A m_SignSingle SignSingle IBM extension, nonstandard extension, combination of SignInit and Sign. Signs or MACs data in one pass, with one call, without constructing intermediate digest state. Does not return any state to host other than the result.
C_VerifyInit* m_VerifyInit VerifyInit Initializes a verification operation.
C_Verify* m_Verify Verify Verifies a signature on single-part data.
C_VerifyUpdate* m_VerifyUpdate VerifyUpdate Continues a multiple-part verification operation.
C_VerifyFinal* m_VerifyFinal VerifyFinal Finishes a multiple-part verification operation.
C_VerifyRecoverInit N/A N/A Initializes a verification operation where the data is recovered from the signature.
C_VerifyRecover N/A N/A Verifies a signature on single-part data, where the data is recovered from the signature.
N/A m_VerifySingle VerifySingle IBM extension, nonstandard extension, combination of VerifyInit and Verify. Signs or MACs data in one pass, with one call, without constructing intermediate digest state. Does not return any state to host other than verification result.
C_DigestEncryptUpdate N/A N/A Continues simultaneous multiple-part digesting and encryption operations.
C_DecryptDigestUpdate N/A N/A Continues simultaneous multiple-part decryption and digesting operations.
C_SignEncryptUpdate N/A N/A Continues simultaneous multiple-part signature and encryption operations.
C_DecryptVerifyUpdate N/A N/A Continues simultaneous multiple-part decryption and verification operations.
C_GenerateKey* m_GenerateKey GenerateKey Generates a secret key.
C_GenerateKeyPair* m_GenerateKeyPair GenerateKeyPair Generates a public-key and private-key pair.
C_WrapKey* m_WrapKey WrapKey Wraps (encrypts) a key.
C_UnwrapKey* m_UnwrapKey UnwrapKey Unwraps (decrypts) a key.
N/A N/A RewrapKeyBlob Transfers ownership of a BLOB that is controlled by the current master key to the new master key when the new master key is committed. This function is a special administration command that is supported only by GREP11.
C_DeriveKey* m_DeriveKey DeriveKey Derives a key from a base key.
C_SeedRandom N/A N/A Adds seed material to the random number generator.
C_GenerateRandom* m_GenerateRandom GenerateRandom Generates random data. The length of the random data cannot be zero and the pointer that points to the random data location cannot be NULL. The maximum length of the random data that can be requested is 1 million bytes.
C_GetFunctionStatus N/A N/A Legacy function that always returns CKR_FUNCTION_NOT_PARALLEL.
C_CancelFunction N/A N/A Legacy function that always returns CKR_FUNCTION_NOT_PARALLEL.

Supported mechanisms

A mechanism is referred to as a process to implement a cryptographic operation. It can vary depending on the level of firmware in the crypto card. The following table shows the mechanisms that are currently supported and how they relate to common GREP11 function categories.

Table 2. Describes the supported GREP11 mechanisms
Function group Supported mechanisms
Encrypt and decrypt CKM_RSA_PKCS1, CKM_RSA_PKCS_OAEP1, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_DES3_ECB, CKM_DES3_CBC, CKM_DES3_CBC_PAD
Sign and verify CKM_RSA_PKCS1, CKM_RSA_PKCS_PSS1, CKM_RSA_X9_311, CKM_SHA1_RSA_PKCS, CKM_SHA256_RSA_PKCS, CKM_SHA224_RSA_PKCS, CKM_SHA384_RSA_PKCS, CKM_SHA512_RSA_PKCS, CKM_SHA1_RSA_PKCS_PSS, CKM_SHA224_RSA_PKCS_PSS, CKM_SHA256_RSA_PKCS_PSS, CKM_SHA384_RSA_PKCS_PSS, CKM_SHA512_RSA_PKCS_PSS, CKM_SHA1_RSA_X9_31, CKM_DSA1, CKM_DSA_SHA1, CKM_ECDSA1, CKM_ECDSA_SHA1, CKM_ECDSA_SHA224, CKM_ECDSA_SHA256, CKM_ECDSA_SHA384, CKM_ECDSA_SHA512, CKM_SHA1_HMAC, CKM_SHA256_HMAC, CKM_SHA384_HMAC, CKM_SHA512_HMAC, CKM_SHA512_224_HMAC, CKM_SHA512_256_HMAC, CKM_IBM_ED25519_SHA5124, CKM_IBM_ECDSA_OTHER2, CKM_IBM_DILITHIUM3
Digest CKM_SHA_1, CKM_SHA224, CKM_SHA256, CKM_SHA384, CKM_SHA512, CKM_SHA512_224, CKM_SHA512_256
Generate key or generate key pair CKM_RSA_PKCS_KEY_PAIR_GEN, CKM_RSA_X9_31_KEY_PAIR_GEN, CKM_DSA_KEY_PAIR_GEN, CKM_DSA_PARAMETER_GEN, CKM_EC_KEY_PAIR_GEN (CKM_ECDSA_KEY_PAIR_GEN), CKM_DH_PKCS_KEY_PAIR_GEN, CKM_DH_PKCS_PARAMETER_GEN, CKM_GENERIC_SECRET_KEY_GEN, CKM_AES_KEY_GEN, CKM_DES2_KEY_GEN, CKM_DES3_KEY_GEN, CKM_IBM_DILITHIUM
Wrap and unwrap CKM_RSA_PKCS, CKM_RSA_PKCS_OAEP, CKM_AES_ECB, CKM_AES_CBC, CKM_AES_CBC_PAD, CKM_DES3_ECB, CKM_DES3_CBC, CKM_DES3_CBC_PAD
Derive CKM_ECDH1_DERIVE, CKM_DH_PKCS_DERIVE, CKM_DES3_ECB_ENCRYPT_DATA, CKM_SHA1_KEY_DERIVATION, CKM_SHA224_KEY_DERIVATION, CKM_SHA256_KEY_DERIVATION, CKM_SHA384_KEY_DERIVATION, CKM_SHA512_KEY_DERIVATION, CKM_IBM_BTC_DERIVE

1: This mechanism supports only single-part operations that are not able to utilize any of the Update GREP11 functions, such as EncryptUpdate, DecryptUpdate, and DigestUpdate.

2: This mechanism is only available for GREP11 SignSingle and VerifySingle operations.

3: This mechanism is not supported by the IBM 4768 crypto card and is not available for SignUpdate and VerifyUpdate operations.

4: This mechanism supports single-part (SignInit, Sign, VerifyInit, Verify), SignSingle, and VerifySingle operations.

Supported attributes and key types

GREP11 attributes define object characteristics that set up how an object can be used and accessed. The following table shows the supported attributes and their relationship to the various supported key types.

Table 3. Describes the supported attributes
Attribute Description Supported key types
CKA_CHECK_VALUE The checksum of the key AES keys, DES keys
CKA_COPYABLE If set to CKA_TRUE, the object can be copied by using the PKCS#11 C_CopyObject function EC private keys, EC public keys, RSA private keys, RSA public keys, DH private keys, DH public keys, DSA private keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_DECRYPT CK_TRUE if key supports decryption. EC private keys, RSA private keys, DH private keys, DSA private keys, AES keys, DES keys, Generic keys
CKA_DERIVE CK_TRUE if key supports key derivation (other keys can be derived from this key). Default is CK_FALSE. EC private keys, EC public keys, RSA private keys, RSA public keys, DH private keys, DH public keys, DSA private keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_EC_PARAMS (CKA_ECDSA_PARAMS) DER-encoding of an ANSI X9.62 Parameters value. EC private keys, EC public keys
CKA_ENCRYPT CK_TRUE if key supports encryption. EC public keys, RSA public keys, DH public keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_EXTRACTABLE CK_TRUE if key is extractable and can be wrapped. EC private keys, RSA private keys, DH private keys, DSA private keys, AES keys, DES keys, Generic keys
CKA_IBM_PQC_PARAMS Supporting parameters for post-quantum cryptography mechanisms. In the case of the Dilithium mechanism CKM_IBM_DILITHIUM, it provides a marshaled object identifier (OID) that represents the strength of Dilithium algorithm to use. Currently, only the strength of Dilithium 4 round 2 is supported. Dilithium keys
CKA_KEY_TYPE Type of key. EC private keys, EC public keys, RSA private keys, RSA public keys, DH private keys, DH public keys, DSA private keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_LOCAL CK_TRUE only if the key was generated locally (on the token) with a C_GenerateKey or C_GenerateKeyPair call or created with a C_CopyObject call as a copy of a key, which had its CKA_LOCAL attribute set to CK_TRUE. EC private keys, EC public keys, RSA private keys, RSA public keys, DH private keys, DH public keys, DSA private keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_MODIFIABLE Set to CK_TRUE if the object can be modified. EC private keys, EC public keys, RSA private keys, RSA public keys, DH private keys, DH public keys, DSA private keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_MODULUS_BITS Length in bits of modulus n. RSA public keys
CKA_PUBLIC_EXPONENT Public exponent e. RSA private keys
CKA_PUBLIC_KEY_INFO DER-encoding of the SubjectPublicKeyInfo for the public key. The value is derived from the underlying public key data and is empty by default. RSA public keys, EC public keys
CKA_SIGN CK_TRUE if key supports signatures where the signature is an appendix to the data. EC private keys, RSA private keys, DH private keys, DSA private keys, AES keys, DES keys, Generic keys
CKA_TRUSTED The certificate or key can be trusted for the application that it was created. EC public keys, RSA public keys, DH public keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_UNWRAP CK_TRUE if key supports unwrapping (can be used to unwrap other keys). EC private keys, RSA private keys, DH private keys, DSA private keys, AES keys, DES keys, Generic keys
CKA_VALUE_LEN Length in bytes of key value. AES keys
CKA_VERIFY CK_TRUE if key supports verification where the signature is an appendix to the data. EC public keys, RSA public keys, DH public keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_WRAP CK_TRUE if key supports wrapping (can be used to wrap other keys). EC public keys, RSA public keys, DH public keys, DSA public keys, AES keys, DES keys, Generic keys
CKA_WRAP_WITH_TRUSTED CK_TRUE if the key can be wrapped only with a wrapping key that has CKA_TRUSTED set to CK_TRUE. Default is CK_FALSE. EC private keys, RSA private keys, DH private keys, DSA private keys, AES keys, DES keys, Generic keys

Supported curves

The EP11 library supports limited types of curves for certain mechanisms. The following table lists the supported curve names for different mechanisms. The number in the curve name means the supported prime bitcount.

Supported curves for generating Elliptic Curve (EC) keys

Mechanism CKM_EC_KEY_PAIR_GEN is supported when you call the GenerateKeyPair function to generate Elliptic Curve (EC) keys. The curve name parameters must be specified as object identifiers (OIDs) by using CKA_EC_PARAMS. You can get the OID by searching the curve name in the OID repository.

Table 4. Supported curve types for generating EC keys
GREP11 mechanism Supported curve types Supported curve names
CKM_EC_KEY_PAIR_GEN National Institute of Standards and Technology (NIST) curves
  • P-192, also known as secp192r1 and prime192v1.
  • P-224, also known as secp224r1.
  • P-256, also known as secp256r1 and prime256v1.
  • P-384, also known as secp384r1.
  • P-521, also known as secp521r.
CKM_EC_KEY_PAIR_GEN Regular Brain pool (BP) curves
  • BP-160R, also known as brainpoolP160r1.
  • BP-192R, also known as brainpoolP192r1.
  • BP-224R, also known as brainpoolP224r1.
  • BP-256R, also known as brainpoolP256r1.
  • BP-320R, also known as brainpoolP320r1.
  • BP-384R, also known as brainpoolP384r1.
  • BP-512R, also known as brainpoolP512r1.
CKM_EC_KEY_PAIR_GEN Twisted Brain pool (BP) curves
  • BP-160T, also known as brainpoolP160t1.
  • BP-192T, also known as brainpoolP192t1.
  • BP-224T, also known as brainpoolP224t1.
  • BP-256T, also known as brainpoolP256t1.
  • BP-320T, also known as brainpoolP320t1.
  • BP-384T, also known as brainpoolP384t1.
  • BP-512T, also known as brainpoolP512t1.
CKM_EC_KEY_PAIR_GEN Standards for Efficient Cryptography (SEC) curves
  • secp256k1
CKM_EC_KEY_PAIR_GEN Edwards curves
  • Ed25519

Supported curves for encrypting digital assets and generating signatures

The following curves are supported for mechanisms that are related to digital asset and digital signature.

Table 5. Supported curve types for encrypting digital assets and signatures
Standard and scheme GREP11 mechanism Supported curve types Supported curve names
BIP32/BIP44 CKM_IBM_BTC_DERIVE Standards for Efficient Cryptography (SEC) curves
  • secp256k1
SLIP10 CKM_IBM_BTC_DERIVE National Institute of Standards and Technology (NIST) curves
  • P-256, also known as secp256r1 and prime256v1
SLIP10 CKM_IBM_BTC_DERIVE Standards for Efficient Cryptography (SEC) curves
  • secp256k1
SLIP10 CKM_IBM_BTC_DERIVE Edwards curves
  • Ed25519
EdDSA CKM_IBM_ED25519_SHA512 Edwards curves
  • Ed25519
Schnorr CKM_IBM_ECDSA_OTHER Standards for Efficient Cryptography (SEC) curves
  • secp256k1
Schnorr CKM_IBM_ECDSA_OTHER National Institute of Standards and Technology (NIST) curves
  • P-256, also known as secp256r1 and prime256v1
Schnorr CKM_IBM_ECDSA_OTHER Regular Brain pool (BP) curves
  • BP-256R, also known as brainpoolP256r1
Schnorr CKM_IBM_ECDSA_OTHER Twisted Brain pool (BP) curves
  • BP-256T, also known as brainpoolP256t1
Schnorr ECSG_IBM_ECSDSA_S256
  • secp256r1
  • secp256k1
  • BP-256R, also known as brainpoolP256r1
  • BP-256T, also known as brainpoolP256t1
Schnorr-Zilliqa ECSG_IBM_ECSDSA_COMPR_MULTI
  • secp256r1
  • secp256k1
  • BP-256R, also known as brainpoolP256r1
  • BP-256T, also known as brainpoolP256t1

Performing cryptographic operations with GREP11 functions

You can perform cryptographic operations by calling GREP11 functions that are defined based on the EP11 implementation of the PKCS #11 specification. The following function descriptions are created based on the PKCS #11 specification, with notes specific to EP11. All parameter definitions are in the original form of EP11. For more information about EP11, see Enterprise PKCS #11 (EP11) Library structure.

EP11 function parameters are mapped to the protocol buffer types that can be found in the following functions. You can learn more about protocol buffer types in Google Developers.

Because the EP11 library is a subset of the PKCS #11 API library, and GREP11 functions are variants from the corresponding EP11 functions, the corresponding functions of EP11 and PKCS #11 are also listed in the GREP11 function tables for your reference.

GREP11 supports any programming language with a gRPC library. At the current stage, only code snippets or examples for Golang and JavaScript are included in the API reference. The content is enriched in later phases. The code snippets are based on the following external GitHub repositories that provide complete examples for using the GREP11 API. Some of the code snippets reference helper functions within the examples repositories.

Retrieving supported crypto algorithms 

You can use the following functions to retrieve cryptographic algorithms or mechanisms that are supported by GREP11. With this information, you can understand the specific mechanisms that can be set when you call a function. For the full list of supported mechanisms, you can also see the mechanisms categorized by function groups.

GetMechanismList

The GetMechanismList function obtains a list of mechanism types that are supported by a token.

Description Binds to EP11 m_GetMechanismList, which is an implementation of PKCS #11 C_GetMechanismList.
Parameters
    message GetMechanismListRequest {
    }
    message GetMechanismListResponse {
      repeated uint64 Mechs = 2;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description Implementation of PKCS #11 C_GetMechanismList.
Parameters
    CK_RV m_GetMechanismList (
      CK_SLOT_ID slot,
      CK_MECHANISM_TYPE_PTR mechs, CK_ULONG_PTR mechslen,
      target_t target
    );
    
Return values A subset of C_GetMechanismList return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

Two ways are available for an application to call C_GetMechanismList:

  1. If pMechanismList is NULL_PTR, then all that C_GetMechanismList does is return (in *pulCount) the number of mechanisms, without returning a list of mechanisms. The contents of *pulCount on entry to C_GetMechanismList has no meaning in this case, and the call returns the value CKR_OK.
  2. If pMechanismList is not NULL_PTR, then *pulCount must contain the size (in terms of CK_MECHANISM_TYPE elements) of the buffer pointed to by pMechanismList. If that buffer is large enough to hold the list of mechanisms, then the list is returned in it, and CKR_OK is returned. If not, then the call to C_GetMechanismList returns the value CKR_BUFFER_TOO_SMALL. In either case, the value *pulCount is set to hold the number of mechanisms.

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

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_GetMechanismList)(
      CK_SLOT_ID slotID,
      CK_MECHANISM_TYPE_PTR pMechanismList,
      CK_ULONG_PTR pulCount
    );
    
Return values CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_ARGUMENTS_BAD.

Code snippets

  • Golang code snippet

    GetMechanismListRequest := &pb.GetMechanismListRequest {
    }
    
    GetMechanismListResponse, err := cryptoClient.GetMechanismList(context.Background(), GetMechanismListRequest)
    
  • JavaScript code snippet

    client.GetMechanismList({}, (err, data) => {
      if (err) throw err;
    
      console.log('MECHANISMS:', data.Mechs);
    });
    

GetMechanismInfo

The GetMechanismInfo Function obtains information about a particular mechanism.

Description Binds to EP11 m_GetMechanismInfo, which is an implementation of PKCS #11 C_GetMechanismInfo.
Parameters
    message GetMechanismInfoRequest {
      uint64 Mech = 2;
    }
    message GetMechanismInfoResponse {
      MechanismInfo MechInfo = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description Implementation of PKCS #11 C_GetMechanismInfo.
Parameters
    CK_RV m_GetMechanismInfo (
      CK_SLOT_ID slot,
      CK_MECHANISM_TYPE mech,
      CK_MECHANISM_INFO_PTR mechInfo,
      target_t target
    );
    
Return values A subset of C_GetMechanismInfo return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_GetMechanismInfo obtains information about a particular mechanism that might be 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.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_GetMechanismInfo)(
      CK_SLOT_ID slotID,
      CK_MECHANISM_TYPE type,
      CK_MECHANISM_INFO_PTR pInfo
    );
    
Return values CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_OK, CKR_SLOT_ID_INVALID, CKR_TOKEN_NOT_PRESENT, CKR_TOKEN_NOT_RECOGNIZED, CKR_ARGUMENTS_BAD.

Code snippets

  • Golang code snippet

    GetMechanismInfoRequest := &pb.GetMechanismInfoRequest {
        Mech: ep11.CKM_RSA_PKCS,
    }
    
    GetMechanismInfoResponse, err := cryptoClient.GetMechanismInfo(context.Background(), GetMechanismInfoRequest)
    
  • JavaScript code snippet

    client.GetMechanismInfo({
      Mech: ep11.CKM_AES_KEY_GEN
      }, (err, data) => {
        if (err) throw err;
    
        console.log('MECHANISM INFO:', data.MechInfo);
    });
    

Generating and deriving keys

GREP11 provides the following functions to generate symmetric and asymmetric cryptographic keys. Based on the mechanism and key length you specify, you can generate various types of keys for various usages. You can also derive a key from a base key to stretch keys into longer keys or to obtain keys of a required format.

GenerateKey

The GenerateKey function generates a secret key for symmetric encryption.

Description Binds to EP11 m_GenerateKey, which is an implementation of PKCS #11 C_GenerateKey.
Parameters
    message GenerateKeyRequest {
      Mechanism Mech = 1;
      map<uint64,AttributeValue> Template = 6;
    }
    message GenerateKeyResponse {
      bytes KeyBytes = 4;
      bytes CheckSum = 5;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_GenerateKey.

TDES keys are generated with proper parity, which is not observable by the host. But it is needed for proper interoperability: other PKCS #11 implementations needs to reject DES keys with parity problems.

If an object is tied to a session, (pin, plen) must be return by Login to that session. Leaving pin NULL creates a public object, one not bound to a login session.

(key, klen) returns the key blob. (csum, clen) contains the key's checksum, that is, the most significant bytes of an all-zero block encrypted by the key. NULL clen is possible, for example for symmetric-key mechanisms without CKA_CHECK_VALUE parameters (such as RC4).

ptempl is used only if the key length (that is, the CKA_VALUE_LEN attribute) is needed by the mechanism. If the mechanism implicitly specifies key size, ptempl is not checked for size.

DSA and DH parameter generation ignores (csum, clen), generating only parameter structures.

DSA, DH parameters (CKM_DSA_PARAMETER_GEN): pass modulus bitcount in CKA_PRIME_BITS of attributes. Writes P,Q,G structure as cleartext output (that is, not a blob).

The pin blob was output from: Login.

PKCS #11 phKey is not mapped to any EP11 parameter. (Host library must bind wrapped key to handle.)

Parameters
    CK_RV m_GenerateKey (
      CK_MECHANISM_PTR mech,
      CK_ATTRIBUTE_PTR template, CK_ULONG templatelen,
      const unsigned char *pin, size_t pinlen,
      unsigned char *key, size_t *keylen,
      unsigned char *checkSum, size_t *checkSumlen,
      target_t target
      );
    
Return values A subset of C_GenerateKey return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_GenerateKey generates a secret key or set of domain parameters, creating a new object. hSession is the session's handle; pMechanism points to the generation mechanism; pTemplate points to the template for the new key or set of domain parameters; ulCount is the number of attributes in the template; phKey points to the location that receives the handle of the new key or set of domain parameters.

If the generation mechanism is for domain parameter generation, the CKA_CLASS attribute has the value CKO_DOMAIN_PARAMETERS; otherwise, it has the value CKO_SECRET_KEY.

Since the type of key or domain parameters to be generated is implicit in the generation mechanism, the template does not need to supply a key type. If it does supply a key type that is inconsistent with the generation mechanism, C_GenerateKey fails and returns the error code CKR_TEMPLATE_INCONSISTENT. The CKA_CLASS attribute is treated in the same way.

If a call to C_GenerateKey cannot support the precise template that is supplied to it, it fails and returns without creating an object.

The object created by a successful call to C_GenerateKey has the CKA_LOCAL attribute set to CK_TRUE.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_GenerateKey)(
      CK_SESSION_HANDLE hSession
      CK_MECHANISM_PTR pMechanism,
      CK_ATTRIBUTE_PTR pTemplate,
      CK_ULONG ulCount,
      CK_OBJECT_HANDLE_PTR phKey
      );
    
Return values CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Setup the AES key's attributes
    keyTemplate := ep11.EP11Attributes{
        ep11.CKA_VALUE_LEN:   keyLen / 8,
        ep11.CKA_WRAP:        false,
        ep11.CKA_UNWRAP:      false,
        ep11.CKA_ENCRYPT:     true,
        ep11.CKA_DECRYPT:     true,
        ep11.CKA_EXTRACTABLE: false,
    }
    
    GenerateKeyRequest := &pb.GenerateKeyRequest{
        Mech:     &pb.Mechanism{Mechanism: ep11.CKM_AES_KEY_GEN},
        Template: util.AttributeMap(keyTemplate),
    }
    
    GenerateKeyResponse, err := cryptoClient.GenerateKey(context.Background(), GenerateKeyRequest)
    
  • JavaScript code snippet

    let keyLen = 128;
    
    let keyTemplate = new util.AttributeMap(
      new util.Attribute(ep11.CKA_VALUE_LEN, keyLen / 8),
      new util.Attribute(ep11.CKA_WRAP, false),
      new util.Attribute(ep11.CKA_UNWRAP, false),
      new util.Attribute(ep11.CKA_ENCRYPT, true),
      new util.Attribute(ep11.CKA_DECRYPT, true),
      new util.Attribute(ep11.CKA_EXTRACTABLE, false),
      new util.Attribute(ep11.CKA_TOKEN, true)
      );
    client.GenerateKey({
      Mech: { Mechanism: ep11.CKM_AES_KEY_GEN },
      Template: keyTemplate,
      KeyId: uuidv4()
    }, (err, data={}) => {
      cb(err, data.KeyBytes, data.CheckSum);
    });
    
    

GenerateKeyPair

The GenerateKeyPair function generates a public key and private key pair.

Description Binds to EP11 m_GenerateKeyPair, which is an implementation of PKCS #11 C_GenerateKeyPair.
Parameters
    message GenerateKeyPairRequest {
      Mechanism Mech = 1;
      map<uint64,AttributeValue> PrivKeyTemplate = 7;
      map<uint64,AttributeValue> PubKeyTemplate = 8;
      }
    message GenerateKeyPairResponse {
      bytes PrivKeyBytes = 5;
      bytes PubKeyBytes = 6;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_GenerateKeyPair.

Keypair parameters are retrieved from pmech, ppublic, and pprivate parameters. For RSA keys, ppublic specifies the modulus size.

In FIPS mode, only RSA moduluses of 1024+256 n bits are supported (integer n). Non-FIPS mode can generate keys of any even number of bits between the limits in the mechanism parameter list.

Public key is formatted as a standard SPKI (subject public key information), readable by most libraries. It is integrity-protected by a transport-key specific MAC, which is not part of the SPKI itself. DSA parameter generation returns a non-SPKI structure in the public key field.

If you tie an object to a session, (pin, plen) must be returned by Login to that session. Leaving pin NULL creates a public object, one that survives the login session.

Returns wrapped private key to (key, klen), public key as a MACed ASN.1/DER structure in (pubkey, pklen).

The following supported parameter combinations with special notes are beyond what are documented by PKCS #11:

RSA keys reject public exponents below 17 (0x11). Control points can further restrict the accepted minimum. The Fermat4 exponent, 0x10001, is controlled by a specific control point, matching public-exponent restrictions of FIPS 186-3 (section B.3.1).

EC keys (CKM_EC_KEY_PAIR_GEN): curve parameters can be specified as OIDs or symbolic names (our namedCurve variant). Supported symbolic names are "P-nnn" for NIST curves (nnn is a supported prime bitcount, 192 - 521), "BP-nnnR" for regular BP curve. (Names must be supplied as ASCII strings, without zero-termination.)

DSA keys (CKM_DSA_KEY_PAIR_GEN): pass P,Q,G structure as the CKA_IBM_STRUCT_PARAMS attribute of public attributes. Individual P,Q,G parameters might not be passed through regular PKCS #11 parameters, they must be combined to a single structure.

DH keys (CKM_DH_PKCS_KEY_PAIR_GEN): pass P,G structure as the CKA_IBM_STRUCT_PARAMS attribute of public attributes. Individual P,G parameters might not be passed through regular PKCS #11 parameters, they must be combined to a single structure. When you select a private-key (X) bitcount, use the XCP_U32_VALUE_BITS attribute. If not present, or an explicit 0 is supplied, bitcount is selected based on P bitcount.

Use of session (Login) state replaces standard use of sessions. The mapping is outside library scope.

The pin blob was output from: Login.

PKCS #11 hSession is not mapped to any EP11 parameter. (The call is not directly associated with any session.)

PKCS #11 phPublicKey is not mapped to any EP11 parameter. (Host library must associate pubkey (SPKI) with handle.)

PKCS #11 phPrivateKey is not mapped to any EP11 parameter. (Host library must associate private key with handle.)

Parameters
    CK_RV m_GenerateKeyPair (
      CK_MECHANISM_PTR mech,
      CK_ATTRIBUTE_PTR pubKeyTemplate, CK_ULONG pubKeyTemplatelen,
      CK_ATTRIBUTE_PTR privKeyTemplate, CK_ULONG privKeyTemplatelen,
      const unsigned char *pin, size_t pinlen,
      unsigned char *privKey, size_t *privKeylen,
      unsigned char *pubKey, size_t *pubKeylen,
      target_t target
      );
    
Return values A subset of C_GenerateKeyPair return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_GenerateKeyPair generates a public and 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.

Since the types of keys to be generated are implicit in the key pair generation mechanism, the templates do not need to supply key types. If one of the templates does supply a key type that is inconsistent with the key generation mechanism, C_GenerateKeyPair fails and returns the error code CKR_TEMPLATE_INCONSISTENT. The CKA_CLASS attribute is treated similarly.

If a call to C_GenerateKeyPair cannot support the precise templates that are supplied to it, it fails and returns without creating any key objects.

A call to C_GenerateKeyPair never creates just one key and returns. A call can fail, and create no keys; or it can succeed, and create a matching public and private key pair.

The key objects created by a successful call to C_GenerateKeyPair have the CKA_LOCAL attributes set to CK_TRUE.

Note carefully the order of the arguments to C_GenerateKeyPair. The last two arguments do not have the same order as they did in the original Cryptoki Version 1.0 document. The order of these two arguments caused some unfortunate confusion.

Parameters
    CK_DEFINE_FUNCTION(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
      );
    
Return values CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Generate RSA key pair
    publicExponent := []byte{0x11}
    publicKeyTemplate := ep11.EP11Attributes{
        ep11.CKA_ENCRYPT:         true,
        ep11.CKA_VERIFY:          true,
        ep11.CKA_MODULUS_BITS:    2048,
        ep11.CKA_PUBLIC_EXPONENT: publicExponent,
        ep11.CKA_EXTRACTABLE:     false,
    }
    privateKeyTemplate := ep11.EP11Attributes{
        ep11.CKA_PRIVATE:     true,
        ep11.CKA_SENSITIVE:   true,
        ep11.CKA_DECRYPT:     true,
        ep11.CKA_SIGN:        true,
        ep11.CKA_EXTRACTABLE: false,
    }
    GenerateKeypairRequest := &pb.GenerateKeyPairRequest{
        Mech:            &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS_KEY_PAIR_GEN},
        PubKeyTemplate:  util.AttributeMap(publicKeyTemplate),
        PrivKeyTemplate: util.AttributeMap(privateKeyTemplate),
    }
    GenerateKeyPairResponse, err := cryptoClient.GenerateKeyPair(context.Background(), GenerateKeypairRequest)
    
  • JavaScript code snippet

    const publicKeyTemplate = new util.AttributeMap(
      new util.Attribute(ep11.CKA_ENCRYPT, true),
      new util.Attribute(ep11.CKA_VERIFY, true),
      new util.Attribute(ep11.CKA_MODULUS_BITS, 2048),
      new util.Attribute(ep11.CKA_PUBLIC_EXPONENT, publicExponent),
      new util.Attribute(ep11.CKA_EXTRACTABLE, false)
    );
    
    const privateKeyTemplate = new util.AttributeMap(
      new util.Attribute(ep11.CKA_PRIVATE, true),
      new util.Attribute(ep11.CKA_SENSITIVE, true),
      new util.Attribute(ep11.CKA_DECRYPT, true),
      new util.Attribute(ep11.CKA_SIGN, true),
      new util.Attribute(ep11.CKA_EXTRACTABLE, false),
    );
    
    client.GenerateKeyPair({
      Mech: {
        Mechanism: ep11.CKM_RSA_PKCS_KEY_PAIR_GEN
      },
      PubKeyTemplate: publicKeyTemplate,
      PrivKeyTemplate: privateKeyTemplate,
      PubKeyId: uuidv4(),
      PrivKeyId: uuidv4()
    }, (err, response) => {
      callback(err, response);
    });
    

DeriveKey

The DeriveKey function derives a key from a base key.

Description Binds to EP11 m_DeriveKey, which is an implementation of PKCS #11 C_DeriveKey.
Parameters
    message DeriveKeyRequest {
        Mechanism Mech = 1;
        bytes BaseKey = 3;
        bytes Data = 4;
        map<uint64,AttributeValue> Template = 8;
    }
    message DeriveKeyResponse {
        bytes NewKeyBytes = 6;
        bytes CheckSum = 7;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DeriveKey.

The basekey,bklen blob must be mapped from the PKCS #11 hBaseKey parameter.

PKCS #11 hSession is not mapped to any EP11 parameter. (The call is not directly associated with any session.)

PKCS #11 phKey is not mapped to any EP11 parameter. (Host library must bind returned key to handle.)

Parameters
    CK_RV m_DeriveKey (
        CK_MECHANISM_PTR mech,
        CK_ATTRIBUTE_PTR template, CK_ULONG templatelen,
        const unsigned char *baseKey, size_t baseKeylen,
        const unsigned char *data, size_t datalen,
        const unsigned char *pin, size_t pinlen,
        unsigned char *newKey, size_t *newKeylen,
        unsigned char *checkSum, size_t *checkSumlen,
        target_t target
    );
    
Return values A subset of C_DeriveKey return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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 chanism; 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; and phKey points to the location that receives the handle of the derived key.

The values of the CKA_SENSITIVE, CKA_ALWAYS_SENSITIVE, CKA_EXTRACTABLE, and KA_NEVER_EXTRACTABLE attributes for the base key affect the values that these attributes can hold for the newly derived key. See the description of each particular key-derivation mechanism in Section 5.16.2 of the PKCS #11 API specification for any constraints of this type.

If a call to C_DeriveKey cannot support the precise template that is supplied to it, it fails and returns without creating any key object.

The key object created by a successful call to C_DeriveKey has the CKA_LOCAL attribute set to CK_FALSE.

Parameters
    CK_DEFINE_FUNCTION(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
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Derive AES key for Alice
    deriveKeyTemplate := ep11.EP11Attributes{
        ep11.CKA_CLASS:     ep11.CKO_SECRET_KEY,
        ep11.CKA_KEY_TYPE:  ep11.CKK_AES,
        ep11.CKA_VALUE_LEN: 128 / 8,
        ep11.CKA_ENCRYPT:   true,
        ep11.CKA_DECRYPT:   true,
    }
    // Extract Bob's EC coordinates
    combinedCoordinates, err := util.GetPubkeyBytesFromSPKI(bobECKeypairResponse.PubKeyBytes)
    if err != nil {
        return nil, fmt.Errorf("Bob's EC public key cannot obtain coordinates: %s", err)
    }
    
    aliceDeriveKeyRequest := &pb.DeriveKeyRequest{
        Mech:     &pb.Mechanism{Mechanism: ep11.CKM_ECDH1_DERIVE, Parameter: util.SetMechParm(combinedCoordinates)},
        Template: util.AttributeMap(deriveKeyTemplate),
        BaseKey:  aliceECKeypairResponse.PrivKeyBytes,
    }
    
    // Derive AES key for Alice
    aliceDeriveKeyResponse, err := cryptoClient.DeriveKey(context.Background(),  aliceDeriveKeyRequest)
    
  • JavaScript code snippet

    //results are created through GenerateKeyPair
    const [alice, bob] = results;
    
    const deriveKeyTemplate = new util.AttributeMap(
    new util.Attribute(ep11.CKA_CLASS, ep11.CKO_SECRET_KEY),
    new util.Attribute(ep11.CKA_KEY_TYPE, ep11.CKK_AES),
    new util.Attribute(ep11.CKA_VALUE_LEN, 128/8),
    new util.Attribute(ep11.CKA_ENCRYPT, true),
    new util.Attribute(ep11.CKA_DECRYPT, true),
    );
    
    const derived = [];
    
    async.eachSeries([
    { PubKey: bob.PubKeyBytes, PrivKey: alice.PrivKeyBytes },
    { PubKey: alice.PubKeyBytes, PrivKey: bob.PrivKeyBytes }
    ], (data, cb) => {
    const combinedCoordinates = util.getPubKeyBytesFromSPKI(data.PubKey);
    
    client.DeriveKey({
      Mech: {
        Mechanism: ep11.CKM_ECDH1_DERIVE,
        ParameterB: combinedCoordinates
      },
      Template: deriveKeyTemplate,
      BaseKey: data.PrivKey
    }, (err, data={}) => {
      if (!err) {
        derived.push(data);
      }
    
      cb(err);
    });
    }
    

Protecting keys

You can protect a key by wrapping it and then decrypt the key by invoking the unwrapping feature.

WrapKey

The WrapKey function wraps (encrypts) a key.

Description Binds to EP11 m_WrapKey, which is an implementation of PKCS #11 C_WrapKey.
Parameters
    message WrapKeyRequest {
        bytes Key = 1;
        bytes KeK = 2;
        bytes MacKey = 3;
        Mechanism Mech = 4;
    }
    message WrapKeyResponse {
        bytes Wrapped = 5;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description Implementation of PKCS #11 C_WrapKey.
Parameters
    CK_RV m_WrapKey (
        const unsigned char *key, size_t keylen,
        const unsigned char *keK, size_t keKlen,
        const unsigned char *macKey, size_t macKeylen,
        const CK_MECHANISM_PTR mech,
        CK_BYTE_PTR wrapped, CK_ULONG_PTR wrappedlen,
        target_t target
    );
    
Return values A subset of C_WrapKey return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_WrapKey wraps (that is, 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.

C_WrapKey uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

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

If the key to be wrapped cannot be wrapped for some token-specific reason, despite its having its CKA_EXTRACTABLE attribute set to CK_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 be used in the following situations:

  • To wrap any secret key with a public key that supports encryption and decryption.
  • To wrap any secret key with any other secret key. Consideration must be given to key size and mechanism strength or the token might not allow the operation.
  • To wrap a private key with any secret key.

Tokens vary in which types of keys can be wrapped with which mechanisms.

To partition the wrapping keys so that they can wrap only a subset of extractable keys, the attribute CKA_WRAP_TEMPLATE can be used on the wrapping key to specify an attribute set that can be compared against the attributes of the key to be wrapped. If all attributes match according to the C_FindObject rules of attribute matching, the wrap operation proceeds. The value of this attribute is an attribute template and the size is the number of items in the template times the size of CK_ATTRIBUTE. If this attribute is not supplied, any template is acceptable. If an attribute is not present, it is not checked. If any attribute mismatch occurs on an attempt to wrap a key, the function returns CKR_KEY_HANDLE_INVALID.

Parameters
    CK_DEFINE_FUNCTION(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
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_HANDLE_INVALID, CKR_KEY_NOT_WRAPPABLE, CKR_KEY_SIZE_RANGE, CKR_KEY_UNEXTRACTABLE, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPING_KEY_HANDLE_INVALID, CKR_WRAPPING_KEY_SIZE_RANGE, CKR_WRAPPING_KEY_TYPE_INCONSISTENT.

Code snippets

  • Golang code snippet

    WrapKeyRequest := &pb.WrapKeyRequest {
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS},
        KeK:  GenerateKeyPairResponse.PubKeyBytes,
        Key:  GenerateKeyResponse.KeyBytes,
    }
    
    WrapKeyResponse, err := cryptoClient.WrapKey(context.Background(), WrapKeyRequest)
    
  • JavaScript code snippet

    client.WrapKey({
      Mech: {
        Mechanism: ep11.CKM_RSA_PKCS
      },
      KeK: rsa.PubKeyBytes,
      Key: aes.KeyBytes
    }, (err, data={}) => {
      cb(err, data.Wrapped);
    });
    

UnwrapKey

The UnwrapKey function unwraps (decrypts) a key.

Description Binds to EP11 m_UnwrapKey, which is an implementation of PKCS #11 C_UnwrapKey.
Parameters
    message UnwrapKeyRequest {
        bytes Wrapped = 1;
        bytes KeK = 2;
        bytes MacKey = 3;
        Mechanism Mech = 5;
        map<uint64,AttributeValue> Template = 9;
    }
    message UnwrapKeyResponse {
        bytes UnwrappedBytes = 7;
        bytes CheckSum = 8;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_UnwrapKey.

uwmech specifies the encryption mechanism that is used to decrypt wrapped data. ptempl is a key(pair) parameter list, specifying how to transform the unwrapped data to a new key (must include CKA_KEY_TYPE).

The generated object is returned under (unwrapped, uwlen) as a blob. Symmetric keys return their key checksum (3 bytes) under (csum, cslen); public-key objects return their public key as an SPKI in (csum, cslen). Both forms are followed by a 4-byte big-endian value, encoding bitcount of the unwrapped key.

When an SPKI is being transformed to a MACed SPKI, one must use CKM_IBM_TRANSPORTKEY as the unwrapping mechanism. This mode supplies the raw SPKI as wrapped data, and ignores the KEK.

UnwrapKey produces parity-adjusted DES keys (within the blobs), but tolerates input with improper parity.

Parameters
    CK_RV m_UnwrapKey (
        const CK_BYTE_PTR wrapped, CK_ULONG wrappedlen,
        const unsigned char *keK, size_t keKlen,
        const unsigned char *macKey, size_t macKeylen,
        const unsigned char *pin, size_t pinlen,
        const CK_MECHANISM_PTR mech,
        const CK_ATTRIBUTE_PTR template, CK_ULONG templatelen,
        unsigned char *unwrapped, size_t *unwrappedlen,
        CK_BYTE_PTR checkSum, CK_ULONG *checkSumlen,
        target_t target
    );
    
Return values A subset of C_UnwrapKey return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_UnwrapKey unwraps (that is, 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 CKA_UNWRAP attribute of the unwrapping key, which indicates whether the key supports unwrapping, must be CK_TRUE.

The new key has the CKA_ALWAYS_SENSITIVE attribute set to CK_FALSE, and the CKA_NEVER_EXTRACTABLE attribute set to CK_FALSE. The CKA_EXTRACTABLE attribute is by default set to CK_TRUE.

Some mechanisms can modify, or attempt to modify. The contents of the pMechanism structure at the same time that the key is unwrapped.

If a call to C_UnwrapKey cannot support the precise template that is supplied to it, it fails and returns without creating any key object.

The key object created by a successful call to C_UnwrapKey has its CKA_LOCAL attribute set to CK_FALSE.

To partition the unwrapping keys so they can unwrap only a subset of keys the attribute CKA_UNWRAP_TEMPLATE can be used on the unwrapping key to specify an attribute set that is added to attributes of the key to be unwrapped. If the attributes do not conflict with the user supplied attribute template, in pTemplate, the unwrap operation proceeds. The value of this attribute is an attribute template and the size is the number of items in the template times the size of CK_ATTRIBUTE. If this attribute is not present on the unwrapping key, then no extra attributes are added. If any attribute conflict occurs on an attempt to unwrap a key, then the function SHALL return CKR_TEMPLATE_INCONSISTENT.

Parameters
    CK_DEFINE_FUNCTION(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
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_CURVE_NOT_SUPPORTED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_DOMAIN_PARAMS_INVALID, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCOMPLETE, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_UNWRAPPING_KEY_HANDLE_INVALID, CKR_UNWRAPPING_KEY_SIZE_RANGE, CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT, CKR_USER_NOT_LOGGED_IN, CKR_WRAPPED_KEY_INVALID, CKR_WRAPPED_KEY_LEN_RANGE.

Code snippets

  • Golang code snippet

    aesUnwrapKeyTemplate := ep11.EP11Attributes{
        ep11.CKA_CLASS:       ep11.CKO_SECRET_KEY,
        ep11.CKA_KEY_TYPE:    ep11.CKK_AES,
        ep11.CKA_VALUE_LEN:   128 / 8,
        ep11.CKA_ENCRYPT:     true,
        ep11.CKA_DECRYPT:     true,
        ep11.CKA_EXTRACTABLE: true, // must be true to be wrapped
    }
    UnwrapKeyRequest := &pb.UnwrapKeyRequest{
        Mech:     &pb.Mechanism{Mechanism: ep11.CKM_RSA_PKCS},
        KeK:      GenerateKeyPairResponse.PrivKeyBytes,
        Wrapped:  WrapKeyResponse.Wrapped,
        Template: util.AttributeMap(aesUnwrapKeyTemplate),
    }
    
    // Unwrap the AES key
    UnwrapKeyResponse, err := cryptoClient.UnwrapKey(context.Background(), UnwrapKeyRequest)
    
  • JavaScript code snippet

    const aesUnwrapKeyTemplate = new util.AttributeMap(
    new util.Attribute(ep11.CKA_CLASS, ep11.CKO_SECRET_KEY),
    new util.Attribute(ep11.CKA_KEY_TYPE, ep11.CKK_AES),
    new util.Attribute(ep11.CKA_VALUE_LEN, 128/8),
    new util.Attribute(ep11.CKA_ENCRYPT, true),
    new util.Attribute(ep11.CKA_DECRYPT, true),
    new util.Attribute(ep11.CKA_EXTRACTABLE, true)
    );
    
    client.UnwrapKey({
        Mech: {
            Mechanism: ep11.CKM_RSA_PKCS
        },
        KeK: rsa.PrivKeyBytes,
        Wrapped: wrapped,
        Template: aesUnwrapKeyTemplate
    }, (err, data={}) => {
        cb(err, wrapped, data.UnwrappedBytes, data.CheckSum);
    });
    

RewrapKeyBlob

The RewrapKeyBlob function reencrypts generated key binary large objects (BLOBs) with the new committed master key that is contained within the HSM. Keys that are reencrypted can be used only after the HSM is finalized with the new committed master key.

This function is a special administration command that is supported only by GREP11. There is no corresponding EP11 function or PKCS #11 function for RewrapKeyBlob.

Description Transfers ownership of a BLOB that is controlled by the current master key to the new master key when the new master key is committed.
Parameters
    message RewrapKeyBlobRequest {
    	bytes WrappedKey = 1;
    }
    message RewrapKeyBlobResponse {
    	bytes RewrappedKey = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.

Code snippets

  • Golang code snippet

    RewrapKeyBlobRequest := &pb.RewrapKeyBlobRequest {
        WrappedKey: GenerateKeyResponse.KeyBytes,
    }
    
    // Rewrap an existing key blob using the HSM's new wrapping key
    RewrapKeyBlobResponse, err := cryptoClient.RewrapKeyBlob(context.Background(),  RewrapKeyBlobRequest)
    
  • JavaScript code snippet

    client.RewrapKeyBlob({
      WrappedKey: wrappedKey
    }, (err, response) => {
      callback(err, response);
    });
    

Retrieving and modifying attributes for keys 

When you generate keys or perform key operations, you define an attribute template as one of the parameters. You can retrieve the attributes for a specific key object and modify some attributes after the key is created.

GetAttributeValue

The GetAttributeValue function obtains an attribute value of an object.

Description Binds to EP11 m_GetAttributeValue, which is an implementation of PKCS #11 C_GetAttributeValue.
Parameters
    message GetAttributeValueRequest {
        bytes Object = 1;
        map<uint64,AttributeValue> Attributes = 3;
    }
    message GetAttributeValueResponse {
        map<uint64,AttributeValue> Attributes = 4;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_GetAttributeValue.

Does not represent or need sessions (part of blob), therefore does not use the hSession parameter.

EP11 uses more straightforward ways to decode, such as enumerating actual values instead of being more generic.

Parameters
    CK_RV m_GetAttributeValue (
        const unsigned char *object, size_t objectlen,
        CK_ATTRIBUTE_PTR attributes, CK_ULONG attributeslen,
        target_t target
    );
    
Return values A subset of C_GetAttributeValue return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

For each (type, pValue, ulValueLen) triple in the template, C_GetAttributeValue performs the following algorithm:

  1. If the specified attribute (that is, the attribute that is specified by the type field) for the object cannot be revealed because the object is sensitive or unextractable, then the ulValueLen field in that triple is modified to hold the value CK_UNAVAILABLE_INFORMATION.
  2. Otherwise, if the specified value for the object is invalid (the object does not possess such an attribute), then the ulValueLen field in that triple is modified to hold the value CK_UNAVAILABLE_INFORMATION.
  3. Otherwise, if the pValue field has the value NULL_PTR, then the ulValueLen field is modified to hold the exact length of the specified attribute for the object.
  4. Otherwise, if the length specified in ulValueLen is large enough to hold the value of the specified attribute for the object, then that attribute is copied into the buffer that is at pValue, and the ulValueLen field is modified to hold the exact length of the attribute.
  5. Otherwise, the ulValueLen field is modified to hold the value CK_UNAVAILABLE_INFORMATION.

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

In the special case of an attribute whose value is an array of attributes, for example CKA_WRAP_TEMPLATE, where it is passed in with pValue not NULL, then if the pValue of elements within the array is NULL_PTR then the ulValueLen of elements within the array is set to the required length. If the pValue of elements within the array is not NULL_PTR, then the ulValueLen element of attributes within the array must reflect the space that the corresponding pValue points to, and pValue is filled in if there is sufficient room. Therefore, it is important to initialize the contents of a buffer before C_GetAttributeValue is called to get such an array value. If any ulValueLen within the array isn't large enough, it is set to CK_UNAVAILABLE_INFORMATION and the function returns CKR_BUFFER_TOO_SMALL, as it does if an attribute in the pTemplate argument has ulValueLen too small. Any attribute whose value is an array of attributes is identifiable by the CKF_ARRAY_ATTRIBUTE set of the attribute type.

The error codes CKR_ATTRIBUTE_SENSITIVE, CKR_ATTRIBUTE_TYPE_INVALID, and CKR_BUFFER_TOO_SMALL do not denote true errors for C_GetAttributeValue. If a call to C_GetAttributeValue returns any of these three values, then the call must nonetheless have processed every attribute in the template that is supplied to C_GetAttributeValue. Each attribute in the template whose value can be returned by the call to C_GetAttributeValue is returned by the call to C_GetAttributeValue.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_GetAttributeValue)(
        CK_SESSION_HANDLE hSession,
        CK_OBJECT_HANDLE hObject,
        CK_ATTRIBUTE_PTR pTemplate,
        CK_ULONG ulCount
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_SENSITIVE, CKR_ATTRIBUTE_TYPE_INVALID, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    // Only retrieve supported EP11 attributes
    attributeList := ep11.EP11Attributes{
        ep11.CKA_DECRYPT: false, // attribute where you would like to retrieve its current value
    }
    
    GetAttributeValueRequest := &pb.GetAttributeValueRequest{
        Object:     GenerateKeyPairResponse.PrivKeyBytes,
        Attributes: util.AttributeMap(attributeList),
    }
    
    GetAttributeValueResponse, err := cryptoClient.GetAttributeValue(context.Background(), GetAttributeValueRequest)
    
  • JavaScript code snippet

    const attributeTemplate = new util.AttributeMap(
    new util.Attribute(ep11.CKA_SIGN, 0)
    );
    
    client.GetAttributeValue({
      Object: keys.PrivKey,
      Attributes: attributeTemplate
    }, (err, response) => {
      callback(err, response);
      console.log('ATTRIBUTE:', response.Attributes);
    });
    

SetAttributeValue

The SetAttributeValue function modifies an attribute value of an object.

Description Binds to EP11 m_SetAttributeValue, which is an implementation of PKCS #11 C_SetAttributeValue.
Parameters
    message SetAttributeValueRequest {
        bytes Object = 1;
        map<uint64,AttributeValue> Attributes = 3;
    }
    message SetAttributeValueResponse {
        bytes Object = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_SetAttributeValue.

Attribute packing: see _GetAttrValue

Currently, Ep11 only sends Boolean attributes, all other attributes are handled by host (and EP11 does not modify arrays, such as WRAP_TEMPLATE).

Does not represent or need sessions (part of blob), therefore does not use the PKCS #11 hSession parameter.

Parameters
    CK_RV m_SetAttributeValue (
        unsigned char *object, size_t objectlen,
        CK_ATTRIBUTE_PTR attributes, CK_ULONG attributeslen,
        target_t target
    );
    
Return values A subset of C_SetAttributeValue return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

Certain objects might not be modified. Calling C_SetAttributeValue on such objects results in the CKR_ACTION_PROHIBITED error code. An application can consult the object's CKA_MODIFIABLE attribute to determine whether an object can be modified.

Only session objects can be modified during a read-only session.

The template can specify new values for any attributes of the object that can be modified. If the template specifies a value of an attribute that 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 4.1.2 of the PKCS #11 API specification for more information.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_SetAttributeValue)(
        CK_SESSION_HANDLE hSession,
        CK_OBJECT_HANDLE hObject,
        CK_ATTRIBUTE_PTR pTemplate,
        CK_ULONG ulCount
    );
    
Return values CKR_ACTION_PROHIBITED, CKR_ARGUMENTS_BAD, CKR_ATTRIBUTE_READ_ONLY, CKR_ATTRIBUTE_TYPE_INVALID, CKR_ATTRIBUTE_VALUE_INVALID, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OBJECT_HANDLE_INVALID, CKR_OK, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SESSION_READ_ONLY, CKR_TEMPLATE_INCONSISTENT, CKR_TOKEN_WRITE_PROTECTED, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Only set supported R/W EP11 attributes
    attributeList := ep11.EP11AttributeP{
        CKA_DECRYPT: true,
    }
    
    SetAttributeValueRequest := &pb.SetAttributeValueRequest{
        Object:     GenerateKeyPair.PrivKeyBytes,
        Attributes: util.AttributeMap(attributeList),
    }
    SetAttributeValueResponse, err := cryptoClient.SetAttributeValue(context.Background(), SetAttributeValueRequest)
    
  • JavaScript code snippet

    const attributeTemplate = new util.AttributeMap(
    new util.Attribute(ep11.CKA_SIGN, true)
    );
    
    client.SetAttributeValue({
      Object: keys.PrivKey,
      Attributes: attributeTemplate
    }, (err, response) => {
      callback(err, response);
    });
    

Generating random data

You can generate high-quality random data, such as initialization values (IVs), PIN, and password, for use in cryptographic operations.

GenerateRandom

The GenerateRandom function generates random data. When you use this function, make sure not to set the length of the random data to be zero and the pointer that points to the random data location to be NULL.

Description Binds to EP11 m_GenerateRandom, which is an implementation of PKCS #11 C_GenerateRandom.
Parameters
    message GenerateRandomRequest {
        uint64 Len = 1;
    }
    message GenerateRandomResponse {
        bytes Rnd = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_GenerateRandom.

GenerateRandom is equivalent to the original PKCS #11 function. Internally, hardware-seeded entropy is passed through a FIPS-compliant DRNG (ANSI X9.31/ISO 18031, depending on Clic version).

The host library could generate random numbers without dispatching to the backend, if suitable functionality would be available on the host. This is not done in the current implementation.

This function does not support a size query.

Parameters
    CK_RV m_GenerateRandom (
        CK_BYTE_PTR rnd, CK_ULONG rndlen,
        target_t target
    );
    
Return values A subset of C_GenerateRandom return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description C_GenerateRandom generates random or pseudo-random data. hSession is the sessions handle; pRandomData points to the location that receives the random data; and ulRandomLen is the length in bytes of the random or pseudo-random data to be generated.
Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_GenerateRandom)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pRandomData,
        CK_ULONG ulRandomLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_ACTIVE, CKR_RANDOM_NO_RNG, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    GenerateRandomRequest := &pb.GenerateRandomRequest {
      Len: 1024,
    }
    
    GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(), GenerateRandomRequest)
    
  • JavaScript code snippet

    client.GenerateRandom({
      Len: ep11.AES_BLOCK_SIZE
    }, (err, response) => {
      callback(err, response);
    });
    

Encrypting and decrypting data

By specifying the cryptographic mechanism, you can perform symmetric or asymmetric encryption and decryption functions. You might need to call a series of subfunctions to encrypt or decrypt data. For example, the multi-part data encryption operation is composed of the EncryptInit, EncryptUpdate, and EncryptFinal suboperations.

EncryptInit

The EncryptInit function initializes an encryption operation. You need to call this function first to perform an encryption.

Description Binds to EP11 m_EncryptInit, which is an implementation of PKCS #11 C_EncryptInit.
Parameters
    message EncryptInitRequest {
        Mechanism Mech = 2;
        bytes Key = 3;
    }
    message EncryptInitResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_EncryptInit.

The (key, klen) blob can be a public-key object, or a secret-key blob. Key type must be consistent with pmech.

For public-key mechanisms, (key, klen) must contain an SPKI. This SPKI is integrity-protected with a MAC key, as returned by GenerateKeyPair or alternatively UnwrapKey. The Encrypt state is created without session restrictions.

For secret-key mechanisms, the Encrypt state inherits object session restrictions from (key, klen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

(key, klen) must be a key blob.

Parameters
    CK_RV m_EncryptInit (
        unsigned char *state, size_t *statelen,
        CK_MECHANISM_PTR mech,
        const unsigned char *key, size_t keylen,
        target_t target
    );
    
Return values A subset of C_EncryptInit return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The CKA_ENCRYPT attribute of the encryption key, which indicates whether the key supports encryption, must be CK_TRUE.

After the application calls 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 obtain the final piece of ciphertext. To process extra data (in single or multiple parts), the application must call C_EncryptInit again.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_EncryptInit)(
        CK_SESSION_HANDLE hSession,
        CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey
    );
    
Return values CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Generate 16 bytes of random data for the initialization vector
    GenerateRandomRequest := &pb.GenerateRandomRequest{
        Len: (uint64)(ep11.AES_BLOCK_SIZE),
    }
    GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(), GenerateRandomRequest)
    if err != nil {
        return nil, fmt.Errorf("GenerateRandom error: %s", err)
    }
    iv := GenerateRandomResponse.Rnd[:ep11.AES_BLOCK_SIZE]
    fmt.Println("Generated IV")
    
    EncryptInitRequest := &pb.EncryptInitRequest{
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Key:  GenerateKeyResponse.KeyBytes,
    }
    
    EncryptInitResponse, err := cryptoClient.EncryptInit(context.Background(), EncryptInitRequest)
    
  • JavaScript code snippet

    client.EncryptInit({
    	Mech: {
        Mechanism: ep11.CKM_AES_CBC_PAD,
        ParameterB: iv
      },
      Key: key
    }, (err, data={}) => {
      cb(err, data.State);
    });
    

Encrypt

The Encrypt function encrypts single-part data. You don't need to perform the EncryptUpdate and EncryptFinal suboperations for a single-part encryption. Before you call this function, make sure to run EncryptInit first.

Description Binds to EP11 m_Encrypt, which is an implementation of PKCS #11 C_Encrypt.
Parameters
    message EncryptRequest {
        bytes State = 1;
        bytes Plain = 2;
    }
    message EncryptResponse {
        bytes Ciphered = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_Encrypt.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: EncryptInit.

Parameters
    CK_RV m_Encrypt (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR plain, CK_ULONG plainlen,
        CK_BYTE_PTR ciphered, CK_ULONG_PTR cipheredlen,
        target_t target
    );
    
Return values A subset of C_Encrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_Encrypt uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The encryption operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the ciphertext.

C_Encrypt cannot be used to terminate a multi-part operation, and must be called after C_EncryptInit without intervening C_EncryptUpdate calls.

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

The plain text and ciphertext can be in the same place, that is, it is OK if pData and pEncryptedData point to the same location.

For most mechanisms, C_Encrypt is equivalent to a sequence of C_EncryptUpdate operations followed by C_EncryptFinal.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_Encrypt)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pData,
        CK_ULONG ulDataLen,
        CK_BYTE_PTR pEncryptedData,
        CK_ULONG_PTR pulEncryptedDataLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    plainText := "Encrypt this message"
    
    EncryptRequest := &pb.EncryptRequest {
        State: EncryptInitResponse.State,
        Plain: plainText,
    }
    
    EncryptResponse, err := cryptoClient.Encrypt(context.Background(), EncryptRequest)
    
  • JavaScript code snippet

    client.Encrypt({
      State: state,
      Plain: Buffer.from(message)
    }, (err, response) => {
      callback(err, response);
    });
    

EncryptUpdate

The EncryptUpdate function continues a multiple-part encryption operation. Before you call this function, make sure to run EncryptInit first.

Description Binds to EP11 m_EncryptUpdate, which is an implementation of PKCS #11 C_EncryptUpdate.
Parameters
    message EncryptUpdateRequest {
        bytes State = 1;
        bytes Plain = 2;
    }
    message EncryptUpdateResponse {
        bytes State = 1;
        bytes Ciphered = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_EncryptUpdate.

The state, slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: EncryptInit.

Parameters
    CK_RV m_EncryptUpdate (
        unsigned char *state, size_t statelen,
        CK_BYTE_PTR plain, CK_ULONG plainlen,
        CK_BYTE_PTR ciphered, CK_ULONG_PTR cipheredlen,
        target_t target
    );
    
Return values A subset of C_EncryptUpdate return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_EncryptUpdate uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The encryption operation must be initialized with C_EncryptInit. This function can 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 plaintext and ciphertext can be in the same place, that is, it is OK if pPart and pEncryptedPart point to the same location.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_EncryptUpdate)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pPart,
        CK_ULONG ulPartLen,
        CK_BYTE_PTR pEncryptedPart,
        CK_ULONG_PTR pulEncryptedPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    plainText := `
    This is a very long message that needs to be encrypted by performing
    multiple EncrypytUpdate functions`
    
    // Use EncryptUpdate if you would like to breakup
    // the encrypt operation into multiple suboperations
    EncryptUpdateRequest1 := &pb.EncryptUpdateRequest {
        State: EncryptInitResponse.State,
        Plain: plainText[:20],
    }
    
    EncryptUpdateResponse, err := cryptoClient.EncryptUpdate(context.Background(), EncryptUpdateRequest1)
    
    ciphertext := EncryptUpdateResponse.Ciphered[:]
    
    EncryptUpdateRequest2 := &pb.EncryptUpdateRequest {
        State: EncryptUpdateResponse.State,
        Plain: plainText[20:],
    }
    
    EncryptUpdateResponse, err := cryptoClient.EncryptUpdate(context.Background(), EncryptUpdateRequest2)
    
    ciphertext = append(ciphertext, EncryptUpdateResponse.Ciphered...)
    
  • JavaScript code snippet

    client.EncryptUpdate({
      State: state,
      Plain: Buffer.from(message.substr(20))
    }, (err, data={}) => {
      cb(err, data.State, Buffer.concat([ciphertext, data.Ciphered]));
    });
    

EncryptFinal

The EncryptFinal function finishes a multiple-part encryption operation.

Description Binds to EP11 m_EncryptFinal, which is an implementation of PKCS #11 C_EncryptFinal.
Parameters
    message EncryptFinalRequest {
        bytes State = 1;
    }
    message EncryptFinalResponse {
        bytes Ciphered = 2;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_EncryptFinal.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: EncryptInit, EncryptUpdate.

Parameters
    CK_RV m_EncryptFinal (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR ciphered, CK_ULONG_PTR cipheredlen,
        target_t target
    );
    
Return values A subset of C_EncryptFinal return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_EncryptFinal uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The encryption operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the ciphertext.

For some multi-part encryption mechanisms, the input plain text 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 fails with return code CKR_DATA_LEN_RANGE.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_EncryptFinal)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pLastEncryptedPart,
        CK_ULONG_PTR pulLastEncryptedPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    EncryptFinalRequest := &pb.EncryptFinalRequest {
        State: EncryptUpdateResponse.State,
    }
    
    EncryptFinalResponse, err := cryptoClient.EncryptFinal(context.Background(), EncryptFinalRequest)
    
  • JavaScript code snippet

    client.EncryptFinal({
      State: state
    }, (err, data={}) => {
      cb(err, Buffer.concat([ciphertext, data.Ciphered]));
    });
    

EncryptSingle

The EncryptSingle function processes data in one pass with one call. It does not return any state to host and returns only the encrypted data. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the EncryptInit and Encrypt functions. It enables you to complete an encryption operation with a single call instead of a series of calls.

Description Binds to EP11 m_EncryptSingle
Parameters
    message EncryptSingleRequest {
        bytes Key = 1;
        Mechanism Mech = 2;
        bytes Plain = 3;
    }
    message EncryptSingleResponse {
        bytes Ciphered = 4;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Non-standard variant of Encrypt. Processes data in one pass, with one call. Does not return any state to host, only encrypted data.

This is the preferred method of encrypting data in one pass for XCP-aware applications. Functionally it is equivalent to EncryptInit followed immediately by Encrypt, but it saves roundtrips, wrapping, and unwrapping.

If the backend supports resident keys, the key can be also a resident-key handle.

See also: Encrypt, EncryptInit, DecryptSingle.

The key blob was output from: GenerateKey, UnwrapKey.

Parameters
    CK_RV m_EncryptSingle (
        const unsigned char *key, size_t keylen,
        CK_MECHANISM_PTR mech,
        CK_BYTE_PTR plain, CK_ULONG plainlen,
        CK_BYTE_PTR ciphered, CK_ULONG_PTR cipheredlen,
        target_t target
    );
    
Return values A subset of C_Encrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    // Generate 16 bytes of random data for the initialization vector
    GenerateRandomRequest := &pb.GenerateRandomRequest{
        Len: (uint64)(ep11.AES_BLOCK_SIZE),
    }
    GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(),  GenerateRandomRequest)
    if err != nil {
        return nil, fmt.Errorf("GenerateRandom error: %s", err)
    }
    
    iv := GenerateRandomResponse.Rnd[:ep11.AES_BLOCK_SIZE]
    fmt.Println("Generated IV")
    
    plainText := "Encrypt this message"
    EncryptSingleRequest := &pb.EncryptSingleRequest{
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Key:  GenerateKeyResponse.KeyBytes,
        Plain: plainText,
    }
    
    EncryptSingleResponse, err := cryptoClient.EncryptSingle(context.Background(), EncryptSingleRequest)
    
  • JavaScript code snippet

    client.EncryptSingle({
      Mech: {
        Mechanism: ep11.CKM_AES_CBC_PAD,
        ParameterB: iv
      },
      Key: aliceDerived.NewKey,
      Plain: Buffer.from(message)
    }, (err, response) => {
      callback(err, response);
    });
    

ReencryptSingle

With the ReencryptSingle function, you can decrypt data with the original key and then encrypt the raw data with a different key in a single call within the cloud HSM. The key types that are used for this operation can be the same or different. This function is an IBM EP11 extension to the standard PKCS #11 specification. This single call is a viable option where a large amount of data needs to be reencrypted with different keys, and bypasses the need to perform a combination of DecryptSingle and EncryptSingle functions for each data item that needs to be reencrypted. It does not return any state to host and returns only the reencrypted data.

Description Binds to EP11 m_ReencryptSingle.
Parameters
    message ReencryptSingleRequest {
        bytes DecKey = 1;
        bytes EncKey = 2;
        Mechanism DecMech = 3;
        Mechanism EncMech = 4;
        bytes Ciphered = 5;
    }
    message ReencryptSingleResponse {
        bytes Reciphered = 6;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Non-standard variant of Encrypt. Processes data in one pass, with one call. Does not return any state to host, only the reencrypted data.

Decrypts data with the original key and then encrypts the raw data with a different key within the cloud HSM.

Parameters
    CK_RV m_ReencryptSingle (
        const unsigned char *dkey, size_t dkeylen,
        const unsigned char *ekey, size_t ekeylen,
        CK_MECHANISM_PTR decmech,
        CK_MECHANISM_PTR encmech,
        CK_BYTE_PTR in, CK_ULONG inlen,
        CK_BYTE_PTR ciphered, CK_ULONG_PTR cipheredlen,
        target_t target
    );
    
Return values A subset of C_Encrypt and C_Decrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    var msg = []byte("Data to encrypt")
    EncryptKey1Request := &pb.EncryptSingleRequest{
        Key:   GenerateKey1Response.KeyBytes,
        Mech:  &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Plain: msg,
    }
    EncryptKey1Response, err := cryptoClient.EncryptSingle(context.Background(), EncryptKey1Request)
    if err != nil {
        return nil, fmt.Errorf("Encrypt error: %s", err)
    }
    
    ReencryptSingleRequest := &pb.ReencryptSingleRequest{
        DecKey:   GenerateKey1Response.KeyBytes, // original key
        EncKey:   GenerateKey2Response.KeyBytes, // new key
        DecMech:  &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        EncMech:  &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Ciphered: RencryptKey1Response.Ciphered,
    }
    
    ReencryptSingleResponse, err := cryptoClient.ReencryptSingle(context.Background(), ReencryptSingleRequest)
    
  • JavaScript code snippet

    client.ReencryptSingle({
    Decmech: {
      Mechanism: mech1,
      ParameterB: iv
    },
    Encmech: {
      Mechanism: mech2,
      ParameterB: iv
    },
    In: encipherState.Ciphered,
    DKey: keyBlob1,
    Ekey: keyBlob2,
    }, (err, response) => {
    callback(err, response);
    });
    

DecryptInit

The DecryptInit function initializes a decryption operation. You need to call this function first to perform a decryption.

Description Binds to EP11 m_DecryptInit, which is an implementation of PKCS #11 C_DecryptInit.
Parameters
    message DecryptInitRequest {
        Mechanism Mech = 2;
        bytes Key = 3;
    }
    message DecryptInitResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description Implementation of PKCS #11 C_DecryptInit.
Parameters
    CK_RV m_DecryptInit (
        unsigned char *state, size_t *statelen,
        CK_MECHANISM_PTR mech,
        const unsigned char *key, size_t keylen,
        target_t target
    );
    
Return values A subset of C_DecryptInit return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The CKA_DECRYPT attribute of the decryption key, which indicates whether the key supports decryption, must be CK_TRUE.

After the application calls 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 obtain the final piece of plaintext. To process extra data (in single or multiple parts), the application must call C_DecryptInit again.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DecryptInit)(
        K_SESSION_HANDLE hSession,
        CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Generate 16 bytes of random data for the initialization vector
    GenerateRandomRequest := &pb.GenerateRandomRequest{
        Len: (uint64)(ep11.AES_BLOCK_SIZE),
    }
    GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(), GenerateRandomRequest)
    if err != nil {
        return nil, fmt.Errorf("GenerateRandom error: %s", err)
    }
    iv := GenerateRandomResponse.Rnd[:ep11.AES_BLOCK_SIZE]
    fmt.Println("Generated IV")
    
    DecryptInitRequest := &pb.DecryptInitRequest{
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Key:  GenerateKeyResponse.KeyBytes,
    }
    
    DecryptInitResponse, err := cryptoClient.DecryptInit(context.Background(), DecryptInitRequest)
    
  • JavaScript code snippet

    client.DecryptInit({
      Mech: {
        Mechanism: ep11.CKM_AES_CBC_PAD,
        ParameterB: iv
      },
      Key: key
    }, (err, data={}) => {
      cb(err, data.State);
    });
    

Decrypt

The Decrypt function decrypts data in a single part. You don't need to perform the DecryptUpdate and DecryptFinal suboperations for a single-part decryption. Before you call this function, make sure to run DecryptInit first.

Description Binds to EP11 m_Decrypt, which is an implementation of PKCS #11 C_Decrypt.
Parameters
    message DecryptRequest {
        bytes State = 1;
        bytes Ciphered = 2;
    }
    message DecryptResponse {
       bytes Plain = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_Decrypt. It does not update (state, slen).

The state, slen binary large object (BLOB) must be mapped from the PKCS #11 hSession parameter. The state BLOB was output from DecryptInit.

Parameters
    CK_RV m_Decrypt (const unsigned char *state, size_t slen,
        CK_BYTE_PTR cipher, CK_ULONG clen,
        CK_BYTE_PTR plain, CK_ULONG_PTR plen,
        target_t target
    );
    
Return values A subset of C_Decrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_Decrypt decrypts encrypted data in a single part.

  • hSession is the session handle.
  • pEncryptedData points to the encrypted data.
  • ulEncryptedDataLen is the length of the encrypted data.
  • pData points to the location that receives the recovered data.
  • pulDataLen points to the location that holds the length of the recovered data.

C_Decrypt uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The decryption operation needs to be 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 with CKR_OK returned to determine the length of the buffer that is needed to hold the plain text.

C_Decrypt cannot be used to terminate a multi-part operation, and needs to be called after C_DecryptInit without intervening C_DecryptUpdate calls.

The ciphertext and plain text can be in the same place, which means it is acceptable if pEncryptedData and pData point to the same location.

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

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_Decrypt)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pEncryptedData,
        CK_ULONG ulEncryptedDataLen,
        CK_BYTE_PTR pData,
        CK_ULONG_PTR pulDataLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    DecryptRequest := &pb.DecryptRequest{
        State:    DecryptInitResponse.State,
        Ciphered: ciphertext, // encrypted data from a previous encrypt operation
    }
    
    DecryptResponse, err := cryptoClient.Decrypt(context.Background(), DecryptRequest)
    
  • JavaScript code snippet

    client.Decrypt({
      State: state,
      Ciphered: ciphertext
    }, (err, response) => {
      callback(err, response);
    });
    

DecryptUpdate

The DecryptUpdate function continues a multiple-part decryption operation. Before you call this function, make sure to run DecryptInit first.

Description Binds to EP11 m_DecryptUpdate, which is an implementation of PKCS #11 C_DecryptUpdate.
Parameters
    message DecryptUpdateRequest {
        bytes State = 1;
        bytes Ciphered = 2;
    }
    message DecryptUpdateResponse {
        bytes State = 1;
        bytes Plain = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DecryptUpdate.

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: DecryptInit.

Parameters
    CK_RV m_DecryptUpdate (
        unsigned char *state, size_t statelen,
        CK_BYTE_PTR ciphered, CK_ULONG cipheredlen,
        CK_BYTE_PTR plain, CK_ULONG_PTR plainlen,
        target_t target
    );
    
Return values A subset of C_DecryptUpdate return values. For more information, see the Return valueschapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_DecryptUpdate uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The decryption operation must be initialized with C_DecryptInit. This function can 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 plain text can be in the same place, that is, it is OK if pEncryptedPart and pPart point to the same location.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DecryptUpdate)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pEncryptedPart,
        CK_ULONG ulEncryptedPartLen,
        CK_BYTE_PTR pPart,
        CK_ULONG_PTR pulPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Use DecryptUpdate if you would like to breakup
    // the decrypt operation into multiple suboperations
    DecryptUpdateRequest1 := &pb.DecryptUpdateRequest{
        State:    DecryptInitResponse.State,
        Ciphered: ciphertext[:16], // encrypted data from a previous encrypt operation
    }
    
    DecryptUpdateResponse, err := cryptoClient.DecryptUpdate(context.Background(), DecryptUpdateRequest1)
    
    plaintext := DecryptUpdateResponse.Plain[:]
    
    DecryptUpdateRequest2 := &pb.DecryptUpdateRequest{
        State:    DecryptUpdateResponse.State,
        Ciphered: ciphertext[16:], // encrypted data from a previous encrypt operation
    }
    
    DecryptUpdateResponse, err := cryptoClient.DecryptUpdate(context.Background(), DecryptUpdateRequest2)
    
    plaintext = append(plaintext, DecryptUpdateResponse.Plain...)
    
  • JavaScript code snippet

    client.DecryptUpdate({
    State: state,
    Ciphered: ciphertext.slice(0, 16)
    }, (err, data={}) => {
    cb(err, data.State, data.Plain);
    });
    

DecryptFinal

The DecryptFinal function finishes a multiple-part decryption operation.

Description Binds to EP11 m_DecryptFinal, which is an implementation of PKCS #11 C_DecryptFinal.
Parameters
    message DecryptFinalRequest {
        bytes State = 1;
    }
    message DecryptFinalResponse {
        bytes Plain = 2;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DecryptFinal.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: DecryptInit, DecryptUpdate.

Parameters
    CK_RV m_DecryptFinal (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR plain, CK_ULONG_PTR plainlen,
        target_t target
    );
    
Return values A subset of C_DecryptFinal return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_DecryptFinal uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The decryption operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the plain text.

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 can be returned.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DecryptFinal)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pLastPart,
        CK_ULONG_PTR pulLastPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_ENCRYPTED_DATA_INVALID, CKR_ENCRYPTED_DATA_LEN_RANGE, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    DecryptFinalRequest := &pb.DecryptFinalRequest {
      State: DecrypUpdateResponse.State,
    }
    
    DecryptFinalResponse, err := cryptoClient.DecryptFinal(context.Background(), DecryptFinalRequest)
    
  • JavaScript code snippet

    client.DecryptFinal({
      State: state
    }, (err, data={}) => {
      cb(err, Buffer.concat([plaintext, data.Plain]));
    });
    

DecryptSingle

The DecryptSingle function processes data in one pass with one call. It does not return any state to host and returns only the decrypted data. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the DecryptInit and Decrypt functions. It enables you to complete a decryption operation with a single call instead of a series of calls.

Description Binds to EP11 m_DecryptSingle.
Parameters
    message DecryptSingleRequest {
        bytes Key = 1;
        Mechanism Mech = 2;
        bytes Ciphered = 3;
    }
    message DecryptSingleResponse {
        bytes Plain = 4;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Non-standard variant of Decrypt. Processes data in one pass, with one call. Does not return any state to host, only decrypted data.

This is the preferred method of encrypting data in one pass for XCP-aware applications. Functionally it is equivalent to DecryptInit followed immediately by Decrypt, but it saves roundtrips, wrapping, and unwrapping.

If the backend supports resident keys, the key can be also a resident-key handle.

See also: Decrypt, DecryptInit, EncryptSingle.

The key blob was output from: GenerateKey, UnwrapKey.

Parameters
    CK_RV m_DecryptSingle (
        const unsigned char *key, size_t keylen,
        CK_MECHANISM_PTR mech,
        CK_BYTE_PTR ciphered, CK_ULONG cipheredlen,
        CK_BYTE_PTR plain, CK_ULONG_PTR plainlen,
        target_t target
    );
    
Return values A subset of C_Decrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    // Generate 16 bytes of random data for the initialization vector
    GenerateRandomRequest := &pb.GenerateRandomRequest{
        Len: (uint64)(ep11.AES_BLOCK_SIZE),
    }
    GenerateRandomResponse, err := cryptoClient.GenerateRandom(context.Background(),  GenerateRandomRequest)
    if err != nil {
        return nil, fmt.Errorf("GenerateRandom error: %s", err)
    }
    iv := GenerateRandomResponse.Rnd[:ep11.AES_BLOCK_SIZE]
    fmt.Println("Generated IV")
    
    DecryptSingleRequest := &pb.DecryptSingleRequest {
        Key:      GenerateKeyResponse.KeyBytes,
        Mech:     &pb.Mechanism{Mechanism: ep11.CKM_AES_CBC_PAD, Parameter: util.SetMechParm(iv)},
        Ciphered: EncryptSingleResponse.Ciphered, // encrypted data from a previous encrypt operation
    }
    
    DecryptSingleResponse, err := cryptoClient.DecryptSingle(context.Background(), DecryptSingleRequest)
    
  • JavaScript code snippet

    client.DecryptSingle({
      Mech: {
        Mechanism: ep11.CKM_AES_CBC_PAD,
        ParameterB: iv
      },
      Key: bobDerived.NewKey,
      Ciphered: ciphertext
    }, (err, response) => {
      callback(err, response);
    });
    

Signing and verifying data

GREP11 provides a set of functions to sign data and verify signatures or message authentication codes (MACs). You might need to call a series of subfunctions to perform a signing operation. For example, the multi-part data signature operation consists of the SignInit, SignUpdate, and SignFinal suboperations.

SignInit

The SignInit function initializes a signature operation. You need to call this function first to perform a signature operation.

Description Binds to EP11 m_SignInit , which is an implementation of PKCS #11 C_SignInit.
Parameters
    message SignInitRequest {
        Mechanism Mech = 2;
        bytes PrivKey = 3;
    }
    message SignInitResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description Implementation of PKCS #11 C_SignInit.
Parameters
    CK_RV m_SignInit (
        unsigned char *state, size_t *statelen,
        CK_MECHANISM_PTR mech,
        const unsigned char *privKey, size_t privKeylen,
        target_t target
    );
    
Return values A subset of C_Decrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The CKA_SIGN attribute of the signature key, which indicates whether the key supports signatures with appendix, must be CK_TRUE.

After the application calls 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 obtain the signature. To process extra data (in single or multiple parts), the application must call C_SignInit again.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_SignInit)(
        CK_SESSION_HANDLE hSession,
        CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    SignInitRequest := &pb.SignInitRequest {
        Mech:    &pb.Mechanism{Mechanism: ep11.CKM_SHA1_RSA_PKCS},
        PrivKey: GenerateKeyPairResponse.PrivKeyBytes,
    }
    
    SignInitResponse, err := cryptoClient.SignInit(context.Background(), SignInitRequest)
    
  • JavaScript code snippet

    client.SignInit({
      Mech: {
        Mechanism: ep11.CKM_SHA1_RSA_PKCS
      },
      PrivKey: keys.PrivKeyBytes
    }, (err, data={}) => {
      cb(err, data.State);
    });
    

Sign

The Sign function signs single-part data. You don't need to perform the SignUpdate and SignFinal suboperations for a single-part signature. Before you call this function, make sure to run SignInit first.

Description Binds to EP11 m_Sign, which is an implementation of PKCS #11 C_Sign.
Parameters
    message SignRequest {
        bytes State = 1;
        bytes Data = 2;
    }
    message SignResponse {
        bytes Signature = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_Sign.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: SignInit.

Parameters
    CK_RV m_Sign (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR signature, CK_ULONG_PTR signaturelen,
        target_t target
    );
    
Return values A subset of C_Sign return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_Sign uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The signing operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the signature.

C_Sign cannot be used to terminate a multi-part operation, and must be called after C_SignInit without intervening C_SignUpdate calls.

For most mechanisms, C_Sign is equivalent to a sequence of C_SignUpdate operations followed by C_SignFinal.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_Sign)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pData,
        CK_ULONG ulDataLen,
        CK_BYTE_PTR pSignature,
        CK_ULONG_PTR pulSignatureLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_FUNCTION_REJECTED.

Code snippets

  • Golang code snippet

    msgHash := sha256.Sum256([]byte("This data needs to be signed"))
    SignRequest := &pb.SignRequest{
        State: SignInitResponse.State,
        Data:  msgHash[:],
    }
    
    // Sign the data
    SignResponse, err := cryptoClient.Sign(context.Background(), SignRequest)
    
  • JavaScript code snippet

    client.Sign({
      State: state,
      Data: dataToSign
    }, (err, data={}) => {
      cb(err, data.Signature);
    });
    

SignUpdate

The SignUpdate function continues a multiple-part signature operation. Before you call this function, make sure to run SignInit first.

Description Binds to EP11 m_SignUpdate, which is an implementation of PKCS #11 C_SignUpdate.
Parameters
    message SignUpdateRequest {
        bytes State = 1;
        bytes Data = 2;
    }
    message SignUpdateResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_SignUpdate.

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: SignInit.

Parameters
    CK_RV m_SignUpdate (
        unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        target_t target
    );
    
Return values A subset of C_SignUpdate return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The signature operation must be initialized with C_SignInit. This function can be called any number of times in succession. A call to C_SignUpdate which results in an error terminates the current signature operation.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_SignUpdate)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pPart,
        CK_ULONG ulPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    // Use SignUpdate if you would like to breakup
    // the sign operation into multiple suboperations
    SignUpdateRequest1 := &pb.SignUpdateRequest {
        State: SignInitResponse.State,
        Data:  msgHash[:16],
    }
    
    SignUpdateResponse, err := cryptoClient.SignUpdate(context.Background(), SignUpdateRequest1)
    
    SignUpdateRequest2 := &pb.SignUpdateRequest {
        State: SignUpdateResponse.State,
        Data:  msgHash[16:],
    }
    
    SignUpdateResponse, err := cryptoClient.SignUpdate(context.Background(), SignUpdateRequest2)
    
  • JavaScript code snippet

    client.SignUpdate({
      State: state,
      Data: digest
    }, (err, response) => {
      callback(err, response);
    });
    

SignFinal

The SignFinal function finishes a multiple-part signature operation.

Description Binds to EP11 m_SignFinal, which is an implementation of PKCS #11 C_SignFinal.
Parameters
    message SignFinalRequest {
        bytes State = 1;
    }
    message SignFinalResponse {
        bytes Signature = 2;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_SignFinal.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: SignInit, SignUpdate.

Parameters
    CK_RV m_SignFinal (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR signature, CK_ULONG_PTR signaturelen,
        target_t target
    );
    
Return values A subset of C_SignFinal return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_SignFinal uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The signing operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the signature.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_SignFinal)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pSignature,
        CK_ULONG_PTR pulSignatureLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN, CKR_FUNCTION_REJECTED.

Code snippets

  • Golang code snippet

    SignFinalRequest := &pb.SignFinalRequest {
        State: SignUpdateResponse.State,
    }
    
    SignFinalResponse, err := cryptoClient.SignFinal(context.Background(), SignFinalRequest)
    
  • JavaScript code snippet

    client.SignFinal({
      State: state
    }, (err, response) => {
      callback(err, response);
    });
    

SignSingle

The SignSingle function signs or MACs data in one pass with one call and without constructing intermediate digest state. It doesn't return any state to host and returns only result. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the SignInit and Sign functions. It enables you to complete a signing operation with a single call instead of a series of calls.

Description Binds to EP11 m_SignSingle.
Parameters
    message SignSingleRequest {
        bytes PrivKey = 1;
        Mechanism Mech = 2;
        bytes Data = 3;
    }
    message SignSingleResponse {
        bytes Signature = 4;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Nonstandard extension, combination of SignInit and Sign. Signs or MACs data in one pass, with one call, without constructing intermediate digest state. Does not return any state to host, only result.

This is the preferred way of signing, without an extra roundtrip, encryption, and decryption. Functionally, SignSingle is equivalent to SignInit followed immediately by Sign.

The (key, klen) blob and the pmech mechanism together must be passable to SignInit.

Multi-data requests for HMAC and CMAC signatures are supported (subvariants 2 and 3).

See also: SignInit, Sign, VerifySingle.

Parameters
    CK_RV m_SignSingle (
        const unsigned char *privKey, size_t privKeylen,
        CK_MECHANISM_PTR mech,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR signature, CK_ULONG_PTR signaturelen,
        target_t target
    );
    
Return values A subset of C_Decrypt return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    msgHash := sha256.Sum256([]byte("This data needs to be signed"))
    SignSingleRequest := &pb.SignSingleRequest {
        PrivKey: GenerateKeyPairResponse.PrivKeyBytes,
        Mech:    &pb.Mechanism{Mechanism: ep11.CKM_SHA256_RSA_PKCS},
        Data:    msgHash[:],
    }
    
    SignSingleResponse, err := cryptoClient.SignSingle(context.Background(), SignSingleRequest)
    
  • JavaScript code snippet

    client.SignSingle({
      Mech: {
        Mechanism: ep11.CKM_ECDSA
      },
      PrivKey: key,
      Data: digest
    }, (err, response) => {
      callback(err, response);
    });
    

VerifyInit

The VerifyInit function initializes a verification operation. You need to call this function first to verify a signature.

Description Binds to EP11 m_VerifyInit, which is an implementation of PKCS #11 C_VerifyInit.
Parameters
    message VerifyInitRequest {
        Mechanism Mech = 2;
        bytes PubKey = 3;
    }
    message VerifyInitResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_VerifyInit. Given a key blob (key, klen), initialize a verify session state in (state, slen). The key blob can be a public key object, or HMAC key bytes. Key blob type must be consistent with pmech.

For public-key mechanisms, (key, klen) must contain an SPKI. This SPKI CKA_UNWRAP can be MACed (such as returned earlier by GenerateKeyPair) or just the SPKI itself (if obtained from an external source, such as a certificate).

If an HMAC operation is initialized, session restrictions of the Verify object are inherited from the HMAC key. Since SPKIs are not tied to sessions, public-key Verify states are session-free.

The key,klen blob must be mapped from the PKCS #11 hKey parameter.

Note: SignInit and VerifyInit are internally the same for HMAC and other symmetric/MAC mechanisms.

Parameters
    CK_RV m_VerifyInit (
        unsigned char *state, size_t *statelen,
        CK_MECHANISM_PTR mech,
        const unsigned char *pubKey, size_t pubKeylen,
        target_t target
    );
    
Return values A subset of C_VerifyInit return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The CKA_VERIFY attribute of the verification key, which indicates whether the key supports verification where the signature is an appendix to the data, must be CK_TRUE.

After the application calls 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 extra data (in single or multiple parts), the application must call C_VerifyInit again.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_VerifyInit)(
        CK_SESSION_HANDLE hSession,
        CK_MECHANISM_PTR pMechanism,
        CK_OBJECT_HANDLE hKey
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_KEY_FUNCTION_NOT_PERMITTED, CKR_KEY_HANDLE_INVALID, CKR_KEY_SIZE_RANGE, CKR_KEY_TYPE_INCONSISTENT, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    VerifyInitRequest := &pb.VerifyInitRequest {
      Mech:   &pb.Mechanism{Mechanism: ep11.CKM_SHA1_RSA_PKCS},
      PubKey: GenerateKeyPairResponse.PubKeyBytes,
    }
    
    VerifyInitResponse, err := cryptoClient.VerifyInit(context.Background(), VerifyInitRequest)
    
  • JavaScript code snippet

    client.VerifyInit({
      Mech: {
        Mechanism: ep11.CKM_SHA1_RSA_PKCS
      },
      PubKey: keys.PubKeyBytes
    }, (err, data={}) => {
      cb(err, signature, data.State);
    });
    

Verify

The Verify function verifies a signature on single-part data. You don't need to perform the VerifyUpdate and VerifyFinal suboperations for a single-part verification. Before you call this function, make sure to run VerifyInit first.

Description Binds to EP11 m_Verify, which is an implementation of PKCS #11 C_Verify.
Parameters
    message VerifyRequest {
        bytes State = 1;
        bytes Data = 2;
        bytes Signature = 3;
    }
    message VerifyResponse {
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_Verify.

Does not update (state, slen).

The relative order of data and signature are reversed relative to VerifySingle.

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: VerifyInit.

Parameters
    CK_RV m_Verify (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR signature, CK_ULONG signaturelen,
        target_t target
    );
    
Return values A subset of C_Verify return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The verification operation must be initialized with C_VerifyInit. A call to C_Verify always terminates the active verification operation.

A successful call to C_Verify needs to 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 is invalid purely based on its length, then CKR_SIGNATURE_LEN_RANGE needs to be returned. In any of these cases, the active signing operation is terminated.

C_Verify cannot be used to terminate a multi-part operation, and must be called after C_VerifyInit without intervening C_VerifyUpdate calls.

For most mechanisms, C_Verify is equivalent to a sequence of C_VerifyUpdate operations followed by C_VerifyFinal.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_Verify)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pData,
        CK_ULONG ulDataLen,
        CK_BYTE_PTR pSignature,
        CK_ULONG ulSignatureLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_INVALID, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE.

Code snippets

  • Golang code snippet

    VerifyRequest := &pb.VerifyRequest {
        State:     VerifyInitResponse.State,
        Data:      msgHash[:],
        Signature: SignResponse.Signature,
    }
    
    VerifyResponse, err := cryptoClient.Verify(context.Background(), VerifyRequest)
    
  • JavaScript code snippet

    client.Verify({
      State: state,
      Data: dataToSign,
      Signature: signature
    }, (err, data={}) => {
      cb(err, signature);
    });
    

VerifyUpdate

The VerifyUpdate function continues a multiple-part verification operation. Before you call this function, make sure to run VerifyInit first.

Description Binds to EP11 m_VerifyUpdate, which is an implementation of PKCS #11 C_VerifyUpdate.
Parameters
    message VerifyUpdateRequest {
        bytes State = 1;
        bytes Data = 2;
    }
    message VerifyUpdateResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_VerifyUpdate.

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: VerifyInit.

Parameters
    CK_RV m_VerifyUpdate (
        unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        target_t target
    );
    
Return values A subset of C_VerifyUpdate return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The verification operation must be initialized with C_VerifyInit. This function can be called any number of times in succession. A call to C_VerifyUpdate that results in an error terminates the current verification operation.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_VerifyUpdate)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pPart,
        CK_ULONG ulPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    // Use VerifyUpdate if you would like to breakup
    // the verify operation into multiple suboperations
    VerifyUpdateRequest1 := &pb.VerifyUpdateRequest {
      State: VerifyInitResponse.State,
      Data:  msgHash[:16],
    }
    
    VerifyUpdateResponse, err := cryptoClient.VerifyUpdate(context.Background(), VerifyUpdateRequest1)
    
    VerifyUpdateRequest2 := &pb.VerifyUpdateRequest {
      State: VerifyUpdateResponse.State,
      Data:  msgHash[16:],
    }
    
    VerifyUpdateResponse, err := cryptoClient.VerifyUpdate(context.Background(), VerifyUpdateRequest2)
    
  • JavaScript code snippet

    client.VerifyUpdate({
      State: state,
      Data: digest
    }, (err, response) => {
      callback(err, response);
    });
    

VerifyFinal

The VerifyFinal function finishes a multiple-part verification operation.

Description Binds to EP11 m_VerifyFinal, which is an implementation of PKCS #11 C_VerifyFinal.
Parameters
    message VerifyFinalRequest {
        bytes State = 1;
        bytes Signature = 2;
    }
    message VerifyFinalResponse {
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_VerifyFinal.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: VerifyInit, VerifyUpdate.

Parameters
    CK_RV m_VerifyFinal (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR signature, CK_ULONG signaturelen,
        target_t target
    );
    
Return values A subset of C_VerifyFinal return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The verification operation must be initialized with C_VerifyInit. A call to C_VerifyFinal always terminates the active verification operation.

A successful call to C_VerifyFinal needs to 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 is invalid based on its length, then CKR_SIGNATURE_LEN_RANGE needs to be returned. In any of these cases, the active verifying operation is terminated.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_VerifyFinal)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pSignature,
        CK_ULONG ulSignatureLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DATA_LEN_RANGE, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_SIGNATURE_INVALID, CKR_SIGNATURE_LEN_RANGE.

Code snippets

  • Golang code snippet

    VerifyFinalRequest := &pb.VerifyFinalRequest {
        State:     VerifyUpdateResponse.State,
        Signature: SignResponse.Signature,
    }
    
    VerifyFinalResponse, err := cryptoClient.VerifyFinal(context.Background(), VerifyFinalRequest)
    
  • JavaScript code snippet

    client.VerifyFinal({
      State: state,
      Signature: signature
    }, (err, response) => {
      callback(err, response);
    });
    

VerifySingle

The VerifySingle function signs or MACs data in one pass with one call and without constructing intermediate digest state. It does not return any state to host and returns only the verification result. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the VerifyInit and Verify functions. It enables you to complete a verification operation with a single call instead of a series of calls.

Description Binds to EP11 m_VerifySingle.
Parameters
    message VerifySingleRequest {
        bytes PubKey = 1;
        Mechanism Mech = 2;
        bytes Data = 3;
        bytes Signature = 4;
    }
    message VerifySingleResponse {
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Nonstandard extension, combination of VerifyInit and Verify. Signs or MACs data in one pass, with one call, without constructing intermediate digest state. Does not return any state to host, only verification result. No size query is available because this function returns a Boolean.

This is the preferred way of verifying a signature, without an extra roundtrip, encryption, decryption. Functionally, VerifySingle is equivalent to VerifyInit followed immediately by a Verify.

The (key, klen) blob and the pmech mechanism together must be passable to VerifyInit.

For public-key mechanisms, (key, klen) must contain an SPKI. This SPKI can be MACed (such as returned as a public key from GenerateKeyPair) or just the SPKI itself (if obtained from an external source, such as a certificate).

See also: VerifyInit, Verify, SignSingle.

Parameters
    CK_RV m_VerifySingle (
        const unsigned char *pubKey, size_t pubKeylen,
        CK_MECHANISM_PTR mech,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR signature, CK_ULONG signaturelen,
        target_t target
    );
    
Return values A subset of C_VerifySingle return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    VerifySingleRequest := &pb.VerifySingleRequest {
        PubKey:    GenerateKeyPairResponse.PubKeyByytes,
        Mech:      &pb.Mechanism{Mechanism: ep11.CKM_SHA256_RSA_PKCS},
        Data:      msgHash[:],
        Signature: SignSingleResponse.Signature,
    }
    
    VerifySingleResponse, err := cryptoClient.VerifySingle(context.Background(), VerifySingleRequest)
    
  • JavaScript code snippet

    client.VerifySingle({
      Mech: {
        Mechanism: ep11.CKM_SHA256_RSA_PKCS
      },
      PubKey: keys.PubKey,
      Data: digest,
      Signature: signature
    }, (err, response) => {
      callback(err, response);
    });
    

Protecting data integrity through message digests

GREP11 provides a set of functions to create message digests that are designed to protect the integrity of a piece of data. You might need to call a series of subfunctions to perform a digesting operation. For example, the multi-part digesting operation consists of the DigestInit, DigestUpdate, and DigestFinal suboperations.

DigestInit

The DigestInit function initializes a message-digesting operation. You need to run this function first to perform a digesting operation.

Description Binds to EP11 m_DigestInit, which is an implementation of PKCS #11 C_DigestInit.
Parameters
    message DigestInitRequest {
        Mechanism Mech = 2;
    }
    message DigestInitResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DigestInit.

Create wrapped digest state.

Note: size queries are supported, but the wrapped state is always returned by the backend, unlike most size queries (which return an output size, instead of actual output). Digest states are sufficiently small that they do not introduce noticeable transport overhead.

During size queries, the host just discards the returned state, and reports blob size (in len). When blob is being returned, len is checked against returned size.

The state,len blob must be mapped from the PKCS #11 hSession parameter. (Host library must tie blob to session.)

Parameters
    CK_RV m_DigestInit (
        unsigned char *state, size_t *len,
        const CK_MECHANISM_PTR mech,
        target_t target
    );
    
Return values A subset of C_DigestInit return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

C_DigestInit initializes a message-digesting operation. hSession is the session’s handle; pMechanism points to the digesting mechanism.

After the application calls C_DigestInit, the application can either call C_Digest to digest data in a single part; or call C_DigestUpdate zero or more times, followed by C_DigestFinal, to digest data in multiple parts. The message-digesting operation is active until the application uses a call to C_Digest or C_DigestFinal to obtain the message digest. To process extra data (in single or multiple parts), the application must call 1C_DigestInit1 again.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DigestInit)(
        CK_SESSION_HANDLE hSession,
        CK_MECHANISM_PTR pMechanism
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_MECHANISM_INVALID, CKR_MECHANISM_PARAM_INVALID, CKR_OK, CKR_OPERATION_ACTIVE, CKR_PIN_EXPIRED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID, CKR_USER_NOT_LOGGED_IN.

Code snippets

  • Golang code snippet

    DigestInitRequest := &pb.DigestInitRequest {
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA256},
    }
    
    DigestInitResponse, err := cryptoClient.DigestInit(context.Background(), DigestInitRequest)
    
  • JavaScript code snippet

    client.DigestInit({
      Mech: {
        Mechanism: ep11.CKM_SHA256
      }
    }, (err, response) => {
      callback(err, response);
    });
    

Digest

The Digest function digests single-part data. You don't need to call the DigestUpdate and DigestFinal functions for digesting single-part data. Before you call this function, make sure to run DigestInit first. When you set parameters, note not to specify the length of the input data to be zero and the pointer that points to the input data location to be NULL.

Description Binds to EP11 m_Digest, which is an implementation of PKCS #11 C_Digest.
Parameters
    message DigestRequest {
        bytes State = 1;
        bytes Data = 2;
    }
    message DigestResponse {
        bytes Digest = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_Digest.

If a digest object has exactly 0 (zero) bytes that are appended to it after creation, in any combination of zero-byte transfers, it can still perform a one-pass Digest, even if it needs to be rejected by a strict implementation.

Does not update (state, slen).

Implementations might perform DigestUpdate, DigestFinal, or Digest calls on cleartext digest objects in host code, bypassing HSM backends altogether. This choice might or might not be visible to host code, and it does not impact the security of the operation (as clear objects might not digest sensitive data).

The state,slen blob must be mapped from the PKCS #11 hSession parameter. The state blob was output from: DigestInit.

Parameters
    CK_RV m_Digest (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR digest, CK_ULONG_PTR digestlen,
        target_t target
    );
    
Return values A subset of C_Digest return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_Digest uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The digest operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the message digest.

C_Digest cannot be used to terminate a multi-part operation, and must be called after C_DigestInit without intervening C_DigestUpdate calls.

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

C_Digest is equivalent to a sequence of C_DigestUpdate operations followed by C_DigestFinal.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_Digest)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pData,
        CK_ULONG ulDataLen,
        CK_BYTE_PTR pDigest,
        CK_ULONG_PTR pulDigestLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    digestData := []byte("Create a digest for this string")
    DigestRequest := &pb.DigestRequest {
        State: DigestInitResponse.State,
        Data:  digestData,
    }
    
    DigestResponse, err := cryptoClient.Digest(context.Background(), DigestRequest)
    
  • JavaScript code snippet

    client.Digest({
        State: state,
        Data: Buffer.from(digestData)
      }, (err, data={}) => {
        cb(err, data.Digest);
      });
    }
    

DigestUpdate

The DigestUpdate function continues a multiple-part digesting operation. Before you call this function, make sure to run DigestInit first. When you set parameters, note not to specify the length of the input data to be zero and the pointer that points to the input data location to be NULL.

Description Binds to EP11 m_DigestUpdate, which is an implementation of PKCS #11 C_DigestUpdate.
Parameters
    message DigestUpdateRequest {
        bytes State = 1;
        bytes Data = 2;
    }
    message DigestUpdateResponse {
        bytes State = 1;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DigestUpdate.

DigestUpdate is polymorphic, accepting both wrapped or clear digest objects, updating state in the same format.

The state,slen blob must be mapped from the PKCS #11 hSession parameter. (Host library must map session to stored state.)

The state blob was output from: DigestInit, DigestUpdate, DigestKey.

See also: DigestInit

Parameters
    CK_RV m_DigestUpdate (
        unsigned char *state, size_t statelen,
        CK_BYTE_PTR data, CK_ULONG datalen,
        target_t target
    );
    
Return values A subset of C_DigestUpdate return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

The message-digesting operation must be initialized with C_DigestInit. Calls to this function and C_DigestKey can be interspersed any number of times in any order. A call to C_DigestUpdate which results in an error terminates the current digest operation.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DigestUpdate)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pPart,
        CK_ULONG ulPartLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    // Use DigestUpdate if you would like to breakup
    // the digest operation into multiple suboperations
    DigestUpdateRequest1 := &pb.DigestUpdateRequest {
        State: DigestInitResponse.State,
        Data:  digestData[:16],
    }
    
    DigestUpdateResponse, err := cryptoClient.DigestUpdate(context.Background(), DigestUpdateRequest1)
    
    DigestUpdateRequest2 := &pb.DigestUpdateRequest {
        State: DigestUpdateResponse.State,
        Data:  digestData[16:],
    }
    
    DigestUpdateResponse, err := cryptoClient.DigestUpdate(context.Background(), DigestUpdateRequest2)
    
  • JavaScript code snippet

    client.DigestUpdate({
      State: state,
      Data: Buffer.from(digestData.substr(0, 64))
    }, (err, data={}) => {
      cb(err, data.State);
    });
    

DigestFinal

The DigestFinal function finishes a multiple-part digesting operation.

Description Binds to EP11 m_DigestFinal, which is an implementation of PKCS #11 C_DigestFinal.
Parameters
    message DigestFinalRequest {
        bytes State = 1;
    }
    message DigestFinalResponse {
        bytes Digest = 2;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Implementation of PKCS #11 C_DigestFinal.

DigestFinal is polymorphic, accepting both wrapped or clear digest objects.

Does not update (state, slen).

The state,slen blob must be mapped from the PKCS #11 hSession parameter.

The state blob was output from: DigestInit, DigestUpdate, DigestKey.

Parameters
    CK_RV m_DigestFinal (
        const unsigned char *state, size_t statelen,
        CK_BYTE_PTR digest, CK_ULONG_PTR digestlen,
        target_t target
    );
    
Return values A subset of C_DigestFinal return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.
Description

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.

C_DigestFinal uses the convention that is described in Section 5.2 of the PKCS #11 API specification on producing output.

The digest operation must be 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 (that is, one that returns CKR_OK) to determine the length of the buffer that is needed to hold the message digest.

Parameters
    CK_DEFINE_FUNCTION(CK_RV, C_DigestFinal)(
        CK_SESSION_HANDLE hSession,
        CK_BYTE_PTR pDigest,
        CK_ULONG_PTR pulDigestLen
    );
    
Return values CKR_ARGUMENTS_BAD, CKR_BUFFER_TOO_SMALL, CKR_CRYPTOKI_NOT_INITIALIZED, CKR_DEVICE_ERROR, CKR_DEVICE_MEMORY, CKR_DEVICE_REMOVED, CKR_FUNCTION_CANCELED, CKR_FUNCTION_FAILED, CKR_GENERAL_ERROR, CKR_HOST_MEMORY, CKR_OK, CKR_OPERATION_NOT_INITIALIZED, CKR_SESSION_CLOSED, CKR_SESSION_HANDLE_INVALID.

Code snippets

  • Golang code snippet

    DigestFinalRequest := &pb.DigestFinalRequest {
        State: DigestUpdateResponse.State,
    }
    
    DigestFinalResponse, err := cryptoClient.DigestFinal(context.Background(), DigestFinalRequest)
    
  • JavaScript code snippet

    client.DigestFinal({
      State: state
    }, (err, response) => {
      callback(err, response);
    });
    

DigestSingle

The DigestSingle function digests data in one pass with one call and without constructing an intermediate digest state and unnecessary roundtrips. This function is an IBM EP11 extension to the standard PKCS #11 specification and is a combination of the DigestInit and Digest functions. It enables you to complete a digesting operation with a single call instead of a series of calls.

Description Binds to EP11 m_DigestSingle.
Parameters
    message DigestSingleRequest {
        Mechanism Mech = 1;
        bytes Data = 2;
    }
    message DigestSingleResponse {
        bytes Digest = 3;
    }
    
Return values Wraps EP11 error into message Grep11Error.
Description

Nonstandard extension, combination of DigestInit and Digest. Digests data in one pass, with one call, without constructing an intermediate digest state, and unnecessary roundtrips.

This is the preferred method of digesting cleartext for XCP-aware applications. Functionally, DigestSingle is equivalent to DigestInit followed immediately by Digest.

If a key needs to be digested, one must use DigestInit and DigestKey, since this function does not handle key blobs.

Does not return any state to host, only digest result. There are no non-PKCS #11 parameters, since everything is used directly from the PKCS #11 call.

Parameters
    CK_RV m_DigestSingle (
        CK_MECHANISM_PTR mech,
        CK_BYTE_PTR data, CK_ULONG datalen,
        CK_BYTE_PTR digest, CK_ULONG_PTR digestlen,
        target_t target
    );
    
Return values A subset of C_DigestSingle return values. For more information, see the Return values chapter of the Enterprise PKCS #11 (EP11) Library structure document.

Code snippets

  • Golang code snippet

    digestData := []byte("Create a digest for this string")
    DigestSingleRequest := &pb.DigestSingleRequest {
        Mech: &pb.Mechanism{Mechanism: ep11.CKM_SHA256},
        Data: digestData,
    }
    
    DigestSingleResponse, err := cryptoClient.DigestSingle(context.Background(), DigestSingleRequest)
    
  • JavaScript code snippet

    client.DigestSingle({
      Mech: {
        Mechanism: ep11.CKM_SHA256
      },
      Data: Buffer.from(digestData)
    }, (err, response) => {
      callback(err, response);
    });
    

Code examples

GREP11 API supports programming languages with gRPC libraries. Two sample GitHub repositories are provided for you to test the GREP11 API: