1

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!

Ali
  • 3,373
  • 5
  • 42
  • 54
hyongsop
  • 91
  • 2
  • 9

0 Answers0