问题
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 passCngKeyBlobFormat.EccPrivateBlob
toCngKey.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