为了账号安全,请及时绑定邮箱和手机立即绑定

无法使用 NCryptExportKey 和 NCryptImportKey 重新导入私钥

无法使用 NCryptExportKey 和 NCryptImportKey 重新导入私钥

C#
慕勒3428872 2023-05-13 15:55:13
我正在尝试重新加载具有不同导出策略的证书私钥以解决此问题。我重复使用此答案中的代码来导出私钥,然后将其导入并将导出策略设置为 AllowPlainTextExport。有了它,我应该能够用重新导入的私钥重建原始证书,并在必要时导出其参数。这是我现在拥有的代码:证书被导出然后导入。但是,导入的私钥不能重新分配给原始证书。我收到“提供的密钥与此证书的公钥不匹配”或“仅支持实现 ICspAsymmetricAlgorithm 的非对称密钥”。我做错了什么吗?
查看完整描述

1 回答

?
交互式爱情

TA贡献1712条经验 获得超3个赞

// Attempt #1


CspParameters parameters = new CspParameters();

parameters.KeyContainerName = importedKeyName;

var rsaKey = new RSACryptoServiceProvider(parameters);

certificate.PrivateKey = rsaKey; // public key doesn't match the private key

CAPI(CspParameters 背后的库)在 Windows 7 或 8.1 上根本无法理解 CNG 中的键;它(理论上)在 10 上支持它,但您肯定必须告诉它密钥位于 CNG (CspParameters.ProviderName) 中。


此处的代码在“Microsoft RSA 和 AES 增强型加密服务提供程序”中使用 ProviderType 24 创建了一个新的 CAPI 密钥,该密钥恰好与您的 CNG 密钥具有相同的本地密钥名称。


您没有指定标志 UseExistingOnly,并且该密钥不存在,所以它创建了一个新的……这就是公钥与证书中的内容不匹配的原因。


// Attempt #2


var rsaCngKey = new RSACng(CngKey.Open(importedKeyName));

certificate.PrivateKey = rsaCngKey; // Only asymmetric keys that implement ICspAsymmetricAlgorithm are supported.

该PrivateKey属性只支持 CAPI,无论是 get 还是 set。该集合使用起来非常危险,因为它不会修改证书对象,它会修改 Windows 证书存储系统中证书的状态……这意味着它还会影响在同一对象上运行的任何其他现在或将来的对象(Windows) 证书。


// Attempt #3

certificate.PrivateKey = null;

X509Certificate2 certWithKey = certificate.CopyWithPrivateKey(rsaKey); // The provided key does not match the public key for this certificate.

这是从尝试 1 创建的相同的新随机密钥。


如果您删除尝试 1,然后合并 2 和 3,您应该以


var rsaCngKey = new RSACng(CngKey.Open(importedKeyName));

X509Certificate2 certWithKey = certificate.CopyWithPrivateKey(rsaCngKey);

这应该有效。(如果您已经将证书导入到证书存储中,您可以只添加certWithKey到证书存储中,这将具有与“每个人都突然知道这个”更新更改相同的更新更改cert.set_PrivateKey,除了您询问证书存储更明显进行更改)


查看完整回答
反对 回复 2023-05-13
  • 1 回答
  • 0 关注
  • 177 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信