尝试在 hsm 上创建密钥时收到 CKR_TEMPLATE_INCONSISTENT 错误。我正在使用 PKCS11 C# 包装器。
public void GenerateKeyByName(ISession session, string keyName, string keyContent,string requestId)
{
byte[] ckaId = session.GenerateRandom(20);
byte[] contentbyte = ConvertUtils.HexStringToBytes(keyContent);
List<IObjectAttribute> objectAttributes = new List<IObjectAttribute>();
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_KEY_TYPE, CKK.CKK_AES));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_TOKEN, true));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ENCRYPT, true));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_DECRYPT, true));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_PRIVATE, true));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_LABEL, keyName));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_ID, ckaId));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_VALUE, contentbyte));
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_VALUE_LEN, 32));
IObjectHandle objectHandle = session.CreateObject(objectAttributes);
}
代码在软 hsm 上工作正常,但在网络 hsm 上我收到此错误。
objectAttributes.Add(session.Factories.ObjectAttributeFactory.Create(CKA.CKA_VALUE_LEN, 32));
这行是后来添加的,但没有帮助。
CKR_TEMPLATE_INCONSISTENT 表示您的属性模板中存在不一致。我看到您正在尝试使用具有已知密钥值的 C_CreateObject 创建密钥。某些 HSM(无论是网络、PCI、USB 还是基于云)可能不允许此类操作。他们还可能不允许将明确的密钥注入 HSM。如果您的 HSM 有该限制,那么我会在您的代码中看到两个问题 -
您应该使用 C_GenerateKey 来生成密钥,或使用 C_GenerateKeyPair 来生成非对称密钥。
从属性模板中删除 (CKA.CKA_VALUE, contentbyte)。您只需要传递 CKA_VALUE_LEN。 HSM 将生成密钥并将值分配给 CKA_VALUE。
如果您想使用已知值(byte[] contentbyte)创建密钥,那么您需要执行以下操作。
希望这有帮助!