将 ECC 私钥 PEM 读入 AsymmetricCipherKeyPair c# bouncy castle

Read ECC private key PEM into AsymmetricCipherKeyPair c# bouncy castle

我使用 Bouncy Castle 生成 PEM 格式的 ECC 密钥对:

var curve = ECNamedCurveTable.GetByName("secp256k1");
var domainParams = new ECDomainParameters(curve.Curve, curve.G, curve.N, curve.H, curve.GetSeed());

var secureRandom = new SecureRandom();
var keyParams = new ECKeyGenerationParameters(domainParams, secureRandom);

var generator = new ECKeyPairGenerator("ECDSA");
generator.Init(keyParams);
AsymmetricCipherKeyPair keyPair = generator.GenerateKeyPair();
TextWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(keyPair.Private);
pemWriter.Writer.Flush();
string pem_privatekey = textWriter.ToString();

我当前的 ECC 私钥是:

-----BEGIN EC PRIVATE KEY-----MIIBUQIBAQQgyDHBaj30dcIsS4otdOXR8ue+rZDwHcGEjxwle3H24W6ggeMwgeACAQEwLAYHKoZIzj0BAQIhAP////////////////////////////////////7///wvMEQEIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABCAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwRBBHm+Zn753LusVaBilc6HCwcCm/zbLc4o2VnygVsW+BeYSDradyajxGVdpPv8DhEIqP0XtEimhVQZnEfQj/sQ1LgCIQD////////////////////+uq7c5q9IoDu/0l6M0DZBQQIBAaFEA0IABHxw0PK0uEvnF1lwhkLmHUlVtQVUrLp/1EcKzfAm6xOL/I6LtQ9nXPxDNhaxf/rPtk3DkZ5CaO0hLr1trCRrJz8=-----END EC PRIVATE KEY-----

我想以充气城堡 ECPrivateKeyParametersAsymmetricCipherKeyPair 格式阅读此 pem 格式。 我正在尝试以下代码。 pem就是上面的私钥串。

PemReader pr = new PemReader(new StringReader(pem));
ECPrivateKeyParameters KeyPair = (ECPrivateKeyParameters)pr.ReadObject();

为什么这个 returns 为空?请指正。

pr.ReadObject() returns 这里有一个 AsymmetricCipherKeyPair 实例。它具有 PrivatePublic 属性,这里 returns 分别是 ECPrivateKeyParametersECPublicKeyParameters 实例,即代码应该是:

PemReader pr = new PemReader(new StringReader(pem));
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pr.ReadObject();
ECPrivateKeyParameters privateKeyParams = (ECPrivateKeyParameters)keyPair.Private;
ECPublicKeyParameters publicKeyParams = (ECPublicKeyParameters)keyPair.Public; // for completeness