How to create and modify objects

All openCryptoki functions that create, modify, or copy objects take a template as one of their arguments, where the template specifies attribute values. Cryptographic functions that create objects, for example, C_GenerateKey, may also contribute some additional attribute values themselves. This depends on which cryptographic mechanism is being performed. In any case, all the required attributes supported by an object class that do not have default values, must be specified during object creation, either in the template or by the function itself.

An application can use the following functions for creating objects:

  • C_CreateObject
  • C_GenerateKey
  • C_GenerateKeyPair
  • C_UnwrapKey
  • C_DeriveKey

In addition, an application can create new objects using the C_CopyObject function.

To create an object with any of these listed functions, the application must supply an appropriate template. This template specifies values for valid attributes. An attribute is valid if it is either one of the attributes described in the PKCS #11 specification or it is an additional vendor-specific attribute supported by the library and token. The attribute values supplied by the template, together with any default attribute values and any attribute values contributed to the object by the object-creation function itself, must fully define the object to create.

Look at the following code example, where function C_CreateObject is used to generate an RSA key, using a template keyTempl to specify the key attributes. One of these attributes, CKA_KEY_TYPE, defines the RSA type of the key:

/*
 * create an RSA key object with C_CreateObject
 */
CK_SESSION_HANDLE hSession;
CK_OBJECT_HANDLE hKey;

CK_OBJECT_CLASS
  dataClass = CKO_DATA,
  certificateClass = CKO_CERTIFICATE,
  keyClass = CKO_PUBLIC_KEY;

CK_KEY_TYPE keyType = CKK_RSA;

CK_ATTRIBUTE keyTemplate[] = {
  {CKA_CLASS, &keyClass, sizeof(keyClass)},
  {CKA_KEY_TYPE, &keyType, sizeof(keyType)},
  {CKA_WRAP, &true, sizeof(true)}, 
  {CKA_MODULUS, modulus, sizeof(modulus)}, 
  {CKA_PUBLIC_EXPONENT, exponent, sizeof(exponent)}
};
CK_RV rc;

rc = C_CreateObject(hSession, keyTemplate, 5, &hKey); 

if (rc != CKR_OK) {
	printf("Error creating key object: 0x%X\n", rc);  return rc;
}

if (rc == CKR_OK) {
      printf("RSA key object creation successful.\n");     
}