EC private key to CngKey in C#

浪尽此生 提交于 2019-12-11 06:05:51

问题


I need to convert a EC private key generated by BouncyCastle to a CngKey in C#. Ultimately, I'm trying to create a PKCS12 that can be imported into the Windows Key Store and am following the information and code example found here.

The EC key pair is generated as follows:

    var ecKeyPairGenerator = new ECKeyPairGenerator("ECDSA");
    ECKeyGenerationParameters ecKeyGenParams = new ECKeyGenerationParameters(SecObjectIdentifiers.SecP384r1, new SecureRandom());
    AsymmetricCipherKeyPair pair = ecKeyPairGenerator.GenerateKeyPair();

To create a CngKey:

PrivateKeyInfo privKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(pair.Private);
CngKey cngPrivKey = CngKey.Import(privKeyStruct.GetDerEncoded(), CngKeyBlobFormat.Pkcs8PrivateBlob);

Searching on the web, the above should work, e.g., see here. Instead, I'm getting an Unknown error exception

(CryptographicException) at System.Security.Cryptography.NCryptNative.ImportKey(). If I pass CngKeyBlobFormat.EccPrivateBlob to CngKey.Import(), I get an invalid data exception.

As a new newbie to both .NET, CNG, and Cryto, I feel I'm overlooking something. Any ideas would be appreciated.

Thanks!


回答1:


It turns out that the pkcs8 content of the private key passed in to the CngKey.Import() method should encode both private and public keys for the method to succeed. And this is consistent with the remarks for the CngKeyBlobFormat.Pkcs8PrivateBlob property found here

So the new question is how to generate in BouncyCastle a pkcs8 byte array encoding of the private key that includes both keys. Pkcs8Generator doesn't do this as the AsymmetricKeyParameter does not have the public key. Any help would be greatly appreciated.

Thanks!



来源:https://stackoverflow.com/questions/45111422/ec-private-key-to-cngkey-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!