123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- using System;
- using System.IO;
- using System.Text;
- namespace vCloud.Server.Utilities
- {
- extern alias WCryptography;
- using WCryptography.Org.BouncyCastle.Asn1.X9;
- using WCryptography.Org.BouncyCastle.Crypto;
- using WCryptography.Org.BouncyCastle.Crypto.Engines;
- using WCryptography.Org.BouncyCastle.Crypto.Parameters;
- /// <summary>
- /// SM2加密
- /// </summary>
- public class SM2EncryptHelper
- {
- public static string _publicKeyPem = "";
- /// <summary>
- /// 初始化公钥
- /// </summary>
- /// <param name="publicKeyPem"></param>
- public static void Init(string publicKeyPem)
- {
- _publicKeyPem = publicKeyPem;
- }
- /// <summary>
- /// SM2加密,采用C1||C3||C2加密序列,使用SM3算法作为C3的一个坐标及明文的摘要值
- /// </summary>
- /// <param name="message"></param>
- /// <param name="publicKeyPem"></param>
- /// <returns>16进制的结果</returns>
- public static string Encrypt(string message)
- {
- try
- {
- if (string.IsNullOrEmpty(message))
- {
- throw new ArgumentException("Message cannot be null or empty.", nameof(message));
- }
- if (string.IsNullOrEmpty(_publicKeyPem))
- {
- throw new ArgumentException("Public key cannot be null or empty.", nameof(_publicKeyPem));
- }
- using (StringReader reader = new StringReader(_publicKeyPem))
- {
- var pemReader = new WCryptography.Org.BouncyCastle.OpenSsl.PemReader(reader);
- object obj = pemReader.ReadObject();
- if (obj is AsymmetricKeyParameter keyParameter)
- {
- var q = ((ECPublicKeyParameters)keyParameter).Q;
- var x9ec = ECNamedCurveTable.GetByName("sm2p256v1");
- var publicParams = new ECPublicKeyParameters(q, new ECDomainParameters(x9ec));
- // 创建SM2公钥加密器
- var engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
- engine.Init(true, publicParams);
- // 对消息进行编码
- byte[] messageBytes = Encoding.UTF8.GetBytes(message);
- byte[] cipherText = engine.ProcessBlock(messageBytes, 0, messageBytes.Length);
- // 返回加密后的数据的base64表示
- string hexString = BitConverter.ToString(cipherText).Replace("-", "").ToUpper();
- return hexString;
- }
- else
- {
- throw new ArgumentException("Invalid public key format.", nameof(_publicKeyPem));
- }
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("Encryption failed: " + ex.Message);
- return null;
- }
- }
- }
- }
|