in src/wrapping/unwrap_with_template.c [250:326]
CK_RV aes_wrap_unwrap_with_trusted(CK_SESSION_HANDLE session,
CK_OBJECT_HANDLE wrapping_key) {
CK_RV rv;
CK_BYTE_PTR wrapped_key = NULL;
CK_OBJECT_HANDLE rsa_public_key = CK_INVALID_HANDLE;
CK_OBJECT_HANDLE rsa_private_key = CK_INVALID_HANDLE;
// validate the wrapping key is marked as trusted
CK_BBOOL cka_trusted_val = false_val;
rv = get_attribute(session, wrapping_key, CKA_TRUSTED, &cka_trusted_val);
if (rv != CKR_OK) {
fprintf(stderr, "Failed to get CKA_TRUSTED attribute on the wrapping key: %lu\n", rv);
goto done;
}
if (cka_trusted_val != true_val) {
fprintf(stderr, "Invalid wrapping key specified. Please specify wrapping key with CKA_TRUSTED set to true\n");
fprintf(stderr, "The CKA_TRUSTED attribute for the wrapping key can be set by using the cloudhsm_mgmt_util:\n\n");
fprintf(stderr, "aws-cloudhsm> loginHSM CO <co-username> <co-password>\n");
fprintf(stderr, "aws-cloudhsm> setAttribute %lu 134 1\n\n", wrapping_key);
rv = CKR_GENERAL_ERROR;
goto done;
}
// Generate keys to be wrapped.
rv = generate_rsa_keypair(session, 2048, &rsa_public_key, &rsa_private_key);
if (rv != CKR_OK) {
fprintf(stderr, "RSA key generation failed: %lu\n", rv);
goto done;
}
printf("rsa_private_key: %lu\n", rsa_private_key);
// Determine how much space needs to be allocated for the wrapped key.
CK_ULONG wrapped_len = 0;
rv = aes_wrap_key(session, wrapping_key, rsa_private_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
rv = aes_wrap_key(session, wrapping_key, rsa_private_key, wrapped_key, &wrapped_len);
if (rv != CKR_OK) {
fprintf(stderr, "Could not wrap key: %lu\n", rv);
goto done;
}
rv = aes_template_unwrap(session, wrapping_key, wrapped_key, wrapped_len);
if (CKR_OK != rv) {
goto done;
}
done:
if (NULL != wrapped_key) {
free(wrapped_key);
}
// 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;
}