我了解到我不能简单地通过 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 上。