在 C# 中从 PEM ed25519 获取 public 和私钥

Get public and private key from PEM ed25519 in C#

我有私钥生成:openssl genpkey -algorithm ed25519 -out private.pem 它看起来像这样:

-----BEGIN PRIVATE KEY-----
MC4CAQAwBQYDK2VwBCIEINTZWUEn/Jt6TV9OxGxjD+6CtqKB3MtcJdFAzFUg3fk/
-----END PRIVATE KEY-----

我还有一个 public 密钥由以下人员生成:openssl pkey -in private.pem -out public.pem 它看起来像这样:

-----BEGIN PUBLIC KEY-----
MCowBQYDK2VwAyEAPBDjfKgiUSIjVLrvsR+pxw5i9unTpr8S5BL04T13r6w=
-----END PUBLIC KEY-----

现在我不知道,如何在 C# 中从这些 PEM 中获取 public 和私钥?在我之前的问题:Generating public ed25519 key with OpenSSL 中,我发现 public 密钥是 X509/SPKI 格式,私钥是 PKCS#8 格式。但是如何在 C# 中从这些格式中获取正确的密钥呢?我尝试使用 X509Certificate2 class 但一无所获。

Ed25519 可以在 .NET 上实现,例如BouncyCastle 并在 .NET Framework 和 .NET Core 上运行。

BouncyCastle 还提供了一种使用 PemReader class.

直接 导入 PEM 密钥的方法

示例:

using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.OpenSsl;
using System;
using System.IO;
using System.Text;

...

//
// Signing
//

// Import private key
string ed25519pkcs8 = @"-----BEGIN PRIVATE KEY-----
                        MC4CAQAwBQYDK2VwBCIEIAYIsKL0xkTkAXDhUN6eDheqODEOGyFZ04jsgFNCFxZf
                        -----END PRIVATE KEY-----";
PemReader pemReaderPrivate = new PemReader(new StringReader(ed25519pkcs8));
Ed25519PrivateKeyParameters ed25519pkcs8Parameters = (Ed25519PrivateKeyParameters)pemReaderPrivate.ReadObject();

// Sign
byte[] dataToSign = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog");
ISigner signer = new Ed25519Signer();
signer.Init(true, ed25519pkcs8Parameters);
signer.BlockUpdate(dataToSign, 0, dataToSign.Length);
byte[] signature = signer.GenerateSignature();
Console.WriteLine("Signature: " + Convert.ToBase64String(signature)); // Signature: MTAK9rOibXN1RBOP3O6cRf7Dut1wS6pdz9xM11NIMjg/G0vEusn0piL1iTUcVZvfPNr4PHZSsjp6qX9HkCKRCw==

//
// Verifying
//

// Import public key
string ed25519x509 = @"-----BEGIN PUBLIC KEY-----
                      MCowBQYDK2VwAyEA3mcwgf2DrWLR3mQ6l2d59bGU6qUStwQrln2+rKlKxoA=
                      -----END PUBLIC KEY-----";
PemReader pemReaderPublic = new PemReader(new StringReader(ed25519x509));
Ed25519PublicKeyParameters ed25519x509Parameters = (Ed25519PublicKeyParameters)pemReaderPublic.ReadObject();

// Verify
ISigner verifier = new Ed25519Signer();
verifier.Init(false, ed25519x509Parameters);
verifier.BlockUpdate(dataToSign, 0, dataToSign.Length);
bool verified = verifier.VerifySignature(signature);
Console.WriteLine("Verification: " + verified); // Verification: True

输出:

Signature: MTAK9rOibXN1RBOP3O6cRf7Dut1wS6pdz9xM11NIMjg/G0vEusn0piL1iTUcVZvfPNr4PHZSsjp6qX9HkCKRCw==
Verification: True