using System;
using System.Text;
using System.Text.RegularExpressions;
using Org.BouncyCastle.Asn1.GM;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
namespace Commons.Secret
{
public sealed class SMCrypto
{
/// <summary>
/// 生成SM2公钥私钥
/// </summary>
/// <param name="publicKey">SM2公钥 16进制</param>
/// <param name="privateKey">SM2私钥 16进制</param>
public static void GenerateSm2KeyHex(out string publicKey, out string privateKey)
{
GenerateSm2Key(out var a, out var b);
publicKey = Hex.ToHexString(a);
privateKey = Hex.ToHexString(b);
}
/// <summary>
/// 生成SM2公钥私钥
/// </summary>
/// <param name="publicKey">SM2公钥</param>
/// <param name="privateKey">SM2私钥</param>
public static void GenerateSm2Key(out byte[] publicKey, out byte[] privateKey)
{
var g = new ECKeyPairGenerator();
g.Init(new ECKeyGenerationParameters(new ECDomainParameters(GMNamedCurves.GetByName("SM2P256V1")), new SecureRandom()));
var k = g.GenerateKeyPair();
publicKey = ((ECPublicKeyParameters)k.Public).Q.GetEncoded(false);
privateKey = ((ECPrivateKeyParameters)k.Private).D.ToByteArray();
}
/// <summary>
/// SM2加密
/// </summary>
/// <param name="sourceData">数据源 16进制字符串</param>
/// <param name="publicKey">公钥 16进制字符串</param>
/// <returns></returns>
public static byte[] Sm2Encrypt(string sourceData, string publicKey)
{
return Sm2Encrypt(Decode(sourceData), Decode(publicKey));
}
/// <summary>
/// SM2加密
/// </summary>
/// <param name="sourceData">数据源</param></
c# 基于BouncyCastle.Crypto的国密sm2,sm4封装,与java版本兼容
于 2022-08-19 14:42:03 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)