How to Export Private Key For ECDiffieHellmanCng

前端 未结 2 1349
故里飘歌
故里飘歌 2021-01-13 05:07

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 er

相关标签:
2条回答
  • 2021-01-13 05:14

    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.

    0 讨论(0)
  • 2021-01-13 05:21

    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.

    0 讨论(0)
提交回复
热议问题