我用于包装和解包公钥和私钥的代码
public void BasicWrapAndUnwrapKeyTest()
{
using (Pkcs11 pkcs11 = new Pkcs11(Settings.Pkcs11LibraryPath, Settings.AppType))
{
// Find first slot with token present
Slot slot = Helpers.GetUsableSlot(pkcs11);
// Open RW session
using (Session session = slot.OpenSession (SessionType.ReadWrite))
{
// Login as normal user
session.Login(CKU.CKU_USER, Settings.NormalUserPin);
// Generate asymetric key pair
ObjectHandle publicKey = null;
ObjectHandle privateKey = null;
GenerateKeyPair(session, out publicKey, out privateKey);
// Generate wrapping key
ObjectHandle secretKey = GenerateKey(session);
// Generate random initialization vector
byte[] iv = session.GenerateRandom(8);
// Specify wrapping mechanism
Mechanism mechanism = new Mechanism(CKM.CKM_DES3_CBC, iv);
// Wrap private key
byte[] wrappedKey = session.WrapKey(mechanism, secretKey, privateKey);
// Define attributes for unwrapped key
List<ObjectAttribute> objectAttributes = new List<ObjectAttribute>();
objectAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_TOKEN, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "unwrapped_private"));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));
objectAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));
// Unwrap private key
ObjectHandle unwrappedKey = session.UnwrapKey(mechanism, secretKey, wrappedKey, objectAttributes);
session.DestroyObject(privateKey);
session.DestroyObject(publicKey);
session.DestroyObject(secretKey);
session.DestroyObject(unwrappedKey);
session.Logout();
}
}
}
运行此代码后,出现以下错误:
消息=“方法C_WrapKey返回了CKR_MECHANISM_INVALID”
答案 0 :(得分:0)
通过返回CKR_MECHANISM_INVALID
错误,您的不受管理的PKCS#11库告诉您“为加密操作指定了无效的机制”。您可以使用GetMechanismInfo()
方法来检查您的非托管库是否支持CKM_DES3_CBC
机制的密钥包装,例如:
MechanismInfo mechanismInfo = selectedSlot.GetMechanismInfo(CKM.CKM_DES3_CBC);
if (!mechanism.MechanismFlags.Wrap)
throw new Exception("Key wrapping with CKM_DES3_CBC is not supported.");