in src/wrapping/aes_no_padding_wrapping.c [23:103]
CK_RV aes_no_padding_wrapping(CK_SESSION_HANDLE session) {
unsigned char *hex_array = NULL;
CK_BYTE_PTR wrapped_key = NULL;
// Generate a wrapping key.
CK_OBJECT_HANDLE wrapping_key = CK_INVALID_HANDLE;
CK_RV rv = generate_aes_token_key_for_wrapping(session, 32, &wrapping_key);
if (rv != CKR_OK) {
fprintf(stderr, "Wrapping key generation failed: %lu\n", rv);
goto done;
}
// Generate key to be wrapped.
// This mechanism does not add padding to the keys.
// Only works for byte-aligned keys such as AES, DES and byte-aligned RSA.
CK_OBJECT_HANDLE aes_key = CK_INVALID_HANDLE;
rv = generate_aes_session_key(session, 32, &aes_key);
if (rv != CKR_OK) {
fprintf(stderr, "AES key generation failed: %lu\n", rv);
goto done;
}
// AES Key Wrap with No Padding.
// This is a vendor defined mechanism.
CK_MECHANISM mech = { CKM_CLOUDHSM_AES_KEY_WRAP_NO_PAD, NULL, 0 };
// Determine how much space needs to be allocated for the wrapped key.
CK_ULONG wrapped_len = 0;
rv = aes_wrap_key(session, &mech, wrapping_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 with No Padding.
rv = aes_wrap_key(session, &mech, wrapping_key, aes_key, wrapped_key, &wrapped_len);
if (rv != CKR_OK) {
fprintf(stderr, "Could not wrap key: %lu\n", rv);
goto done;
}
// Display the hex string.
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 = aes_unwrap_key(session, &mech, wrapping_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 key is a token key, so we have to clean it up.
CK_RV cleanup_rv = funcs->C_DestroyObject(session, wrapping_key);
if (CKR_OK != cleanup_rv) {
fprintf(stderr, "Failed to delete wrapping key with rv: %lu\n", cleanup_rv);
}
return rv;
}