in src/wrapping/rsa_wrapping.c [382:461]
CK_RV rsa_aes_wrap(CK_SESSION_HANDLE session) {
CK_BYTE_PTR wrapped_key = NULL;
unsigned char *hex_array = NULL;
CK_OBJECT_HANDLE rsa_public_key = CK_INVALID_HANDLE;
CK_OBJECT_HANDLE rsa_private_key = CK_INVALID_HANDLE;
// Generate a wrapping key.
CK_OBJECT_HANDLE aes_key = CK_INVALID_HANDLE;
CK_RV rv = generate_aes_key(session, 32, &aes_key);
if (rv != CKR_OK) {
fprintf(stderr, "Wrapping key generation failed: %lu\n", rv);
goto done;
}
// Generate keys to be wrapped.
rv = generate_wrapping_keypair(session, 2048, &rsa_public_key, &rsa_private_key);
if (rv != CKR_OK) {
fprintf(stderr, "RSA key generation failed: %lu\n", rv);
goto done;
}
// Determine how much space needs to be allocated for the wrapped key.
CK_ULONG wrapped_len = 0;
rv = rsa_aes_wrap_key(session, rsa_public_key, aes_key, NULL, &wrapped_len);
if (rv != CKR_OK) {
fprintf(stderr, "Could not determine size of wrapped key: %lu\n", rv);
goto done;
}
wrapped_key = malloc(wrapped_len);
if (NULL == wrapped_key) {
fprintf(stderr, "Could not allocate memory to hold wrapped key\n");
goto done;
}
// Wrap the key and display the hex string.
rv = rsa_aes_wrap_key(session, rsa_public_key, aes_key, wrapped_key, &wrapped_len);
if (rv != CKR_OK) {
fprintf(stderr, "Could not wrap key: %lu\n", rv);
goto done;
}
bytes_to_new_hexstring(wrapped_key, wrapped_len, &hex_array);
if (!hex_array) {
fprintf(stderr, "Could not allocate hex array\n");
goto done;
}
printf("Wrapped key: %s\n", hex_array);
// Unwrap the key back into the HSM to verify everything worked.
CK_OBJECT_HANDLE unwrapped_handle = CK_INVALID_HANDLE;
rv = rsa_aes_unwrap_key(session, rsa_private_key, CKK_AES, wrapped_key, wrapped_len, &unwrapped_handle);
if (rv != CKR_OK) {
fprintf(stderr, "Could not unwrap key: %lu\n", rv);
goto done;
}
printf("Unwrapped bytes as object %lu\n", unwrapped_handle);
done:
if (NULL != wrapped_key) {
free(wrapped_key);
}
if (NULL != hex_array) {
free(hex_array);
}
// The wrapping keys are token keys, so we have to clean it up.
CK_RV public_cleanup_rv = funcs->C_DestroyObject(session, rsa_public_key);
if (CKR_OK != public_cleanup_rv) {
fprintf(stderr, "Failed to delete public key with rv: %lu\n", public_cleanup_rv);
}
CK_RV private_cleanup_rv = funcs->C_DestroyObject(session, rsa_private_key);
if (CKR_OK != private_cleanup_rv) {
fprintf(stderr, "Failed to delete private key with rv: %lu\n", private_cleanup_rv);
}
return rv;
}