aws-samples / aws-cloudhsm-pkcs11-examples

Sample applications demonstrating how to use the CloudHSM PKCS#11 library
Other
52 stars 37 forks source link

Setting id for generated key #65

Closed chetagra closed 1 year ago

chetagra commented 1 year ago

How can I set a particular id to generated ECC key pair

kladd commented 1 year ago

Modifying the ID after a key has been created isn't supported, but you can set an ID when generating the key pair using the CKA_ID attribute in each of the public and private key templates. The ID is expected to be the same for the public and private keys, but it's not required. The ID does need to be unique for each key pair however.

Here's an example using CKA_ID and CKA_LABEL when generating an EC key pair. I'm also setting CKA_TOKEN to true here so that the keys are persistent.

diff --git a/src/generate/ec_generate.c b/src/generate/ec_generate.c
index 6389ec3..1ad79a1 100644
--- a/src/generate/ec_generate.c
+++ b/src/generate/ec_generate.c
@@ -36,16 +36,25 @@ CK_RV generate_ec_keypair(CK_SESSION_HANDLE session,
                           CK_OBJECT_HANDLE_PTR private_key) {
     CK_RV rv;
     CK_MECHANISM mech = {CKM_EC_KEY_PAIR_GEN, NULL, 0};
+    CK_BYTE *pub_label = "my_ec_pub_key";
+    CK_BYTE *pvt_label = "my_ec_pvt_key";
+
+    CK_BYTE *keypair_id = "kp_id";
+

     CK_ATTRIBUTE public_key_template[] = {
             {CKA_VERIFY,    &true_val,       sizeof(CK_BBOOL)},
-            {CKA_TOKEN,     &false_val,      sizeof(CK_BBOOL)},
-            {CKA_EC_PARAMS, named_curve_oid, named_curve_oid_len}
+            {CKA_TOKEN,     &true_val,       sizeof(CK_BBOOL)},
+            {CKA_EC_PARAMS, named_curve_oid, named_curve_oid_len},
+            {CKA_LABEL,     pub_label,       strlen(pub_label)},
+            {CKA_ID,        keypair_id,      strlen(keypair_id)},
     };

     CK_ATTRIBUTE private_key_template[] = {
             {CKA_SIGN,  &true_val,  sizeof(CK_BBOOL)},
-            {CKA_TOKEN, &false_val, sizeof(CK_BBOOL)},
+            {CKA_TOKEN, &true_val,  sizeof(CK_BBOOL)},
+            {CKA_LABEL, pvt_label,  strlen(pvt_label)},
+            {CKA_ID,    keypair_id, strlen(keypair_id)},
     };

     rv = funcs->C_GenerateKeyPair(session,

PKCS11 attributes: http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/csd03/pkcs11-base-v2.40-csd03.html#_Toc395183265 PKCS11 C_GenerateKeyPair example: http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/csd03/pkcs11-base-v2.40-csd03.html#_Toc323024157

chetagra commented 1 year ago

thnx

chetagra commented 1 year ago

Screenshot from 2023-04-11 16-17-40 I am getting following issue when trying to add CKA_ID value

bellow is the code I am using Screenshot from 2023-04-11 16-24-49