runliuv

runliuv@cnblogs

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

使用 openssl 生成国密 公钥 私钥 公私钥 EC PRIVATE KEY

使用 openssl 生成国密 公钥 私钥 公私钥 EC PRIVATE KEY

"-----BEGIN EC PRIVATE KEY-----"

"-----END EC PRIVATE KEY-----"

 

OpenSSL 3.0+(Ubuntu 22.04/24.04 等) 命令:

# 生成 SM2 私钥
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:sm2 -out sm2_private_key.pem

# 导出公钥
openssl pkey -in sm2_private_key.pem -pubout -out sm2_public_key.pem

 

C# .NET 读取 (需要引用  BouncyCastle 库)

string privateKeyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sm2certs", "opensslgen1", "sm2_private_key.txt");
string publicKeyPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "sm2certs", "opensslgen1", "sm2_public_key.txt");

string mchPrivateKeyBase64 = File.ReadAllText(privateKeyPath);
mchPrivateKeyBase64 = mchPrivateKeyBase64.Replace("-----BEGIN EC PRIVATE KEY-----", "").Replace("-----END EC PRIVATE KEY-----", "")
    .Replace("-----BEGIN PRIVATE KEY-----", "").Replace("-----END PRIVATE KEY-----", "");

string platPubKeyBase64 = File.ReadAllText(publicKeyPath);
platPubKeyBase64 = platPubKeyBase64.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "")
    .Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "");

 AsymmetricKeyParameter mchPrivateKey = PrivateKeyFactory.CreateKey(Convert.FromBase64String(mchPrivateKeyBase64));
 if (mchPrivateKey != null)
 {
     Console.WriteLine("私钥正常:");
 }

AsymmetricKeyParameter platPubKeyObj = PublicKeyFactory.CreateKey(Convert.FromBase64String(platPubKeyBase64));
if (platPubKeyObj != null)
{
    Console.WriteLine("公钥正常:");
}

 

 

--

posted on 2026-07-21 14:52  runliuv  阅读(9)  评论(0)    收藏  举报