1

我的打包和解包公钥和私钥的代码

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();
        }
    }
}

运行此代码后,我收到以下错误:

Message = "方法 C_WrapKey 返回 CKR_MECHANISM_INVALID"

4

1 回答 1

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.");
于 2018-09-11T05:14:02.227 回答