Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Export Private Key For ECDiffieHellmanCng

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?

like image 419
Kevin Junghans Avatar asked Dec 10 '13 21:12

Kevin Junghans


2 Answers

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.

like image 149
vcsjones Avatar answered Nov 09 '22 20:11

vcsjones


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.

like image 22
Haney Avatar answered Nov 09 '22 21:11

Haney