如何使用带有私钥的pkcs#11Interop加密消息?

时间:2018-09-20 15:19:27

标签: c# encryption private-key pkcs#11

生成这样的密钥对

public void GenerateKeyPair(Session session, out ObjectHandle publicKeyHandle, out ObjectHandle privateKeyHandle)
    {
        // The CKA_ID attribute is intended as a means of distinguishing multiple key pairs held by the same subject
        byte[] ckaId = session.GenerateRandom(20);

        // Prepare attribute template of new public key
        List<ObjectAttribute> publicKeyAttributes = new List<ObjectAttribute>();
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, false));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "user_public"));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_VERIFY_RECOVER, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_WRAP, true));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_MODULUS_BITS, 2048));
        publicKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PUBLIC_EXPONENT, new byte[] { 0x01, 0x00, 0x01 }));

        // Prepare attribute template of new private key
        List<ObjectAttribute> privateKeyAttributes = new List<ObjectAttribute>();
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_PRIVATE, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_LABEL, "user_private"));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ID, ckaId));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SENSITIVE, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_DECRYPT, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_SIGN_RECOVER, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_EXTRACTABLE, true));

        // Specify key generation mechanism
        Mechanism mechanism = new Mechanism(CKM.CKM_RSA_PKCS_KEY_PAIR_GEN);

        // Generate key pair
        session.GenerateKeyPair(mechanism, publicKeyAttributes, privateKeyAttributes, out publicKeyHandle, out privateKeyHandle);
    }

当我尝试使用session.encrypt(Mechanism,privateKey,message)时出现错误。如何使用带有私钥的pkcs#11Interop加密消息?

0 个答案:

没有答案