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?
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:
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.
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.