5

我正在尝试从ECDiffieHellmanCng对象的新实例中导出密钥,以便稍后使用相同的密钥创建它的实例。但是在尝试导出它时出现错误。

//Create new ECDiffieHellmanCng which automatically creates new keys
var ecdh = new ECDiffieHellmanCng();
//Export the keys
var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob);

当我使用消息“请求的操作不受支持”调用Export方法时,我收到 CryptographicException 。在代码中放置一些断点后,看起来它甚至在执行该方法之前就抛出了异常。查看 Export 方法的定义,它装饰有SecuritySafeCriticalAttribute,所以我怀疑这个属性实际上是在抛出异常。是什么导致了这个异常?如何保存密钥,以便以后创建相同 ECDiffieHellmanCng 对象的实例?

4

2 回答 2

12

默认情况下,密钥不可导出 - 它们安全地存储在 KSP 中。创建密钥时,需要将其标记为允许导出。例子:

var ecdh = new ECDiffieHellmanCng(CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, new CngKeyCreationParameters {ExportPolicy = CngExportPolicies.AllowPlaintextExport}));
//Export the keys
var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob);

为了简单起见,我们可以直接从 CngKey 导出它,如果您只想创建一个新密钥并导出私钥,则不使用该算法。

var cngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, new CngKeyCreationParameters {ExportPolicy = CngExportPolicies.AllowPlaintextExport});
var privateKey = cngKey.Export(CngKeyBlobFormat.EccPrivateBlob);

您可以使用导出的 blob 重新创建 CngKey,CngKey.Import(yourBlob, CngKeyBlobFormat.EccPrivateBlob)并将其传递给 ECDiffieHellmanCng 的构造函数。


SecuritySafeCriticalAttribute 是.NET 安全透明模型的一部分。这不是你错误的根源。

于 2013-12-10T21:47:33.743 回答
1

我相信您指定了错误的 BLOB 格式。尝试:

var privateKey = ecdh.Key.Export(CngKeyBlobFormat.Pkcs8PrivateBlob);

如果失败,您需要设置允许导出私钥的密钥策略。有关您的问题的更多详细信息,请参阅此答案:https ://stackoverflow.com/a/10274270/2420979。

于 2013-12-10T21:39:13.720 回答