How to Export Private Key For ECDiffieHellmanCng

2019-02-18 23:55发布

问题:

I am trying to export the keys from a new instance of a ECDiffieHellmanCng object so I can create an instance of it later with the same keys. But I am getting an error when trying to export it.

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

I am getting a CryptographicException when I call the Export method with the message "The requested operation is not supported." After putting some breakpoints in the code it looks like it is throwing the exception before even executing the method. Looking at the definition of the Export method it is adorned with a SecuritySafeCriticalAttribute so I am suspicious that this attribute is actually throwing the exception. What is causing this exception? How can I save the keys so I can create an instance of the same ECDiffieHellmanCng object at a later time?

回答1:

By default, keys aren't exportable - they are securely stored in the KSP. When creating the key, it needs to be marked allowed for export. Example:

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

To make this simpler, we can just export it from the CngKey directly and not use the algorithm if all you want to do is create a new key and export the private key.

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

You can re-create the CngKey from the exported blob by using CngKey.Import(yourBlob, CngKeyBlobFormat.EccPrivateBlob) and passing that to the constructor of ECDiffieHellmanCng.


SecuritySafeCriticalAttribute is part of the .NET Security Transparency model. It is not the source of your errors.



回答2:

I believe you are specifying the wrong BLOB format. Try:

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

If that fails, you need to set up a key policy that allows private key export. See this answer: https://stackoverflow.com/a/10274270/2420979 for more details on your problem.