Kev*_*ans 4 c# security public-key-encryption diffie-hellman cng
我正在尝试从ECDiffieHellmanCng对象的新实例导出密钥,以便稍后可以使用相同的密钥创建它的实例.但是我在尝试导出它时遇到错误.
//Create new ECDiffieHellmanCng which automatically creates new keys
var ecdh = new ECDiffieHellmanCng();
//Export the keys
var privateKey = ecdh.Key.Export(CngKeyBlobFormat.EccPrivateBlob);
Run Code Online (Sandbox Code Playgroud)
当我使用消息" 不支持请求的操作 " 调用Export方法时,我收到CryptographicException .在代码中放入一些断点之后,它甚至在执行方法之前抛出了异常.查看Export方法的定义,它使用SecuritySafeCriticalAttribute进行装饰,因此我怀疑此属性实际上是在抛出异常.导致此异常的原因是什么?如何保存密钥以便以后可以创建相同ECDiffieHellmanCng对象的实例?
vcs*_*nes 11
默认情况下,密钥不可导出 - 它们安全地存储在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);
Run Code Online (Sandbox Code Playgroud)
为了简化这一点,我们可以直接从CngKey导出它,如果您只想创建一个新密钥并导出私钥,则不要使用该算法.
var cngKey = CngKey.Create(CngAlgorithm.ECDiffieHellmanP256, null, new CngKeyCreationParameters {ExportPolicy = CngExportPolicies.AllowPlaintextExport});
var privateKey = cngKey.Export(CngKeyBlobFormat.EccPrivateBlob);
Run Code Online (Sandbox Code Playgroud)
您可以通过使用CngKey.Import(yourBlob, CngKeyBlobFormat.EccPrivateBlob)并将其传递给ECDiffieHellmanCng的构造函数,从导出的blob重新创建CngKey.
SecuritySafeCriticalAttribute是.NET安全透明度模型的一部分.它不是您错误的来源.