如何将 ECDiffieHellmanPublicKey 实例转换为 .net 框架中的 DER 文件?

How to convert ECDiffieHellmanPublicKey instance to DER file in .net framework?

我有以下代码:

ECDiffieHellman ecdh = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
ECDiffieHellmanPublicKey ecdhPublic = ecdh.PublicKey;

如何将 ECDiffieHellmanPublicKey 实例 (ecdhPublic) 导出到 DER 编码文件中?

使用 BouncyCastle (http://www.bouncycastle.org/) 您可以将 ECDH public 密钥导出到 DER 编码的 ANS.1 对象

X9ECParameters ecP = NistNamedCurves.GetByName("P-256");
ECDomainParameters ecSpec = new ECDomainParameters(ecP.Curve, ecP.G, ecP.N, ecP.H, ecP.GetSeed());
ECKeyPairGenerator g = new ECKeyPairGenerator();
g.Init(new ECKeyGenerationParameters(ecSpec, new SecureRandom()));

AsymmetricCipherKeyPair server = g.GenerateKeyPair();
ECPublicKeyParameters serverPub = (ECPublicKeyParameters)server.Public;
var result = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(serverPub).GetDerEncoded();