Export EC private key from BouncyCastle and import into CngKey or ECDsaCng?

荒凉一梦 提交于 2019-12-06 13:35:09

After much hair-pulling, reading RFCs and studying the byte arrays generated by BouncyCastle and CngKey.Export I have found the answer.

The issue lies in how BouncyCastle encodes the EC key to DER/Pkcs8 format. The two RFCs which are relevant to this particular issue are RFC5915 (which is not a standard but instead a consensus document) and RFC5480. They state that curve parameters must be specified using named curves referenced in RFC5480. The BouncyCastle implementation of PKCS8/DER exporting will export the entire curve specification (implicit curve) which is not compliant with these two specs when you create the AsymmetricCipherKeyPair using the wrong generator parameters. You must use the ECKeyGenerationParameters which specify a named curve.

The following must be used (as far as I can tell) when creating interoperable keys in BouncyCastle:

string namedCurve = "prime256v1";
ECKeyPairGenerator pGen = new ECKeyPairGenerator();
ECKeyGenerationParameters genParam = new ECKeyGenerationParameters(
  X962NamedCurves.GetOid(namedCurve)   
  new SecureRandom());
pGen.Init(genParam);

AsymmetricCipherKeyPair keyPair = pGen.GenerateKeyPair();

The CngKey can be created by importing the key using the Der encoded bytes:

var bcKeyInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
var pkcs8Blob = bcKeyInfo.GetDerEncoded();
var importedKey = CngKey.Import(pkcs8Blob, CngKeyBlobFormat.Pkcs8PrivateBlob);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!