代码之家  ›  专栏  ›  技术社区  ›  D.R.

PKCS#11打开HSM的私钥

  •  1
  • D.R.  · 技术社区  · 7 年前

    我明白了,我不能简单地通过PKCS#11将私钥传输到我的HSM,我需要先将其包装,然后在HSM上打开。所以我临时在我们的HSM上创建了一个DES3密钥,然后我想用它包装(加密)我的RSA私钥,然后我想在HSM上打开它。

    我的代码如下所示:

        // Create temporary DES3 key for wrapping/unwrapping
        var tempKeyAttributes = new List<ObjectAttribute>();
        tempKeyAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_SECRET_KEY));
        tempKeyAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_DES3));
        tempKeyAttributes.Add(new ObjectAttribute(CKA.CKA_ENCRYPT, true));
        tempKeyAttributes.Add(new ObjectAttribute(CKA.CKA_UNWRAP, true));
        var tempKey = session.GenerateKey(new Mechanism(CKM.CKM_DES3_KEY_GEN), tempKeyAttributes);
    
        // Encrypt (wrap) the RSA private key
        var encryptedPrivateKeyParamsD = session.Encrypt(new Mechanism(CKM.CKM_DES3_ECB), tempKey, privateKeyParams.D);
    
        // Define how the new RSA private key should look like on the HSM
        var privateKeyAttributes = new List<ObjectAttribute>();
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_CLASS, CKO.CKO_PRIVATE_KEY));
        privateKeyAttributes.Add(new ObjectAttribute(CKA.CKA_KEY_TYPE, CKK.CKK_RSA));
        [...]
    
        // Unwrap the private key onto the HSM
        var privateKeyHandle = session.UnwrapKey(new Mechanism(CKM.CKM_DES3_ECB), tempKey, encryptedPrivateKeyParamsD, privateKeyAttributes);
    

    CKR_INVALID_MECHANISM .

    encryptedPrivateKeyParamsD

    有没有办法解决这个问题?我只想使用PKCS#11以编程方式将现有的RSA私钥放到我们的HSM上。

    1 回复  |  直到 7 年前
        1
  •  2
  •   D.R.    7 年前

    var unencryptedPrivateKey = PrivateKeyInfoFactory.CreatePrivateKeyInfo(
            new RsaPrivateCrtKeyParameters(
                new BigInteger(1, privateKeyParams.Modulus),
                new BigInteger(1, privateKeyParams.Exponent),
                new BigInteger(1, privateKeyParams.D),
                new BigInteger(1, privateKeyParams.P),
                new BigInteger(1, privateKeyParams.Q),
                new BigInteger(1, privateKeyParams.DP),
                new BigInteger(1, privateKeyParams.DQ),
                new BigInteger(1, privateKeyParams.InverseQ))).GetEncoded();
    
    var result = new MemoryStream();
    session.Encrypt(new Mechanism(CKM.CKM_DES3_CBC_PAD, iv), tempKey, new MemoryStream(unencryptedPrivateKey), result);
    var encryptedPrivateKey = result.ToArray();
    
    [...]
    
    var privateKeyHandle = session.UnwrapKey(new Mechanism(CKM.CKM_DES3_CBC_PAD, iv), tempKey, encryptedPrivateKey, privateKeyAttributes);
    
    推荐文章