PKCS#11接口C_CreateObject创建AES密钥参数错误,求排查模板问题
Let's walk through the issues in your template that are likely causing the parameter error when creating a 128-bit AES key:
Incorrect AES Key Length
You're targeting a 128-bit AES key, which requires 16 bytes of material—but yourkey_valuearray only has 8 bytes (0x01 to 0xef). PKCS#11 strictly validates that key lengths match the specified key type (CKK_AES requires 16, 24, or 32 bytes for 128, 192, 256-bit keys respectively). Fix this by expanding your key array to 16 bytes, e.g.:CK_BYTE key_value[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe };CKA_LABEL Size Mismatch
Usingsizeof("key")gives you 4 (since the string includes a hidden null terminator), but PKCS#11 expects the length of the actual label text (without the null byte). Most implementations will reject this or treat the null as part of the label, leading to invalid parameters. Replace it withstrlen("key")(or hardcode 3):{CKA_LABEL, (CK_VOID_PTR)"key", strlen("key")}Clarify: Generate vs. Import Key
If you want the PKCS#11 device to generate a random AES-128 key (instead of importing your own pre-defined value), remove theCKA_VALUEattribute entirely and addCKA_VALUE_LENset to 16:CK_ULONG key_len = 16; // Add this to your template instead of CKA_VALUE {CKA_VALUE_LEN, &key_len, sizeof(key_len)}If you do intend to import a pre-made key, just fix the key length and label size as above—though double-check that your device allows key imports (some HSMs require specific permissions).
Quick Sanity Checks
- Make sure your
sessionis valid: it should be opened withC_OpenSessionand (if required) authenticated withC_Login. - Look closely at the error code you get (e.g.,
CKR_KEY_SIZE_RANGEconfirms a length issue,CKR_ATTRIBUTE_VALUE_INVALIDpoints to label or other attribute problems). This will narrow down the root cause faster.
- Make sure your
Corrected Code Example
CK_OBJECT_HANDLE hKey; CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY; CK_KEY_TYPE keyType = CKK_AES; CK_BBOOL _true = TRUE; CK_BBOOL _false = FALSE; // 128-bit AES key (16 bytes) CK_BYTE key_value[] = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe }; CK_ATTRIBUTE keyTemplate[] = { {CKA_CLASS, &keyClass, sizeof(keyClass)}, {CKA_KEY_TYPE, &keyType, sizeof(keyType)}, {CKA_ENCRYPT, &_true, sizeof(_true)}, {CKA_DECRYPT, &_true, sizeof(_true)}, {CKA_TOKEN, &_true, sizeof(_true)}, /* token object */ {CKA_PRIVATE, &_false, sizeof(_false)}, /* public object */ {CKA_VALUE, key_value, sizeof(key_value)}, {CKA_LABEL, (CK_VOID_PTR)"key", strlen("key")} // Fixed label length }; rv = pfunc11->C_CreateObject(session, keyTemplate, sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE), &hKey); if (rv != CKR_OK) { printf("ERROR: rv=0x%08X: C_CreateObject:\n", (unsigned int)rv); return false; }
内容的提问来源于stack exchange,提问作者ejohnson

