SM2EncryptHelper.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. namespace vCloud.Server.Utilities
  5. {
  6. extern alias WCryptography;
  7. using WCryptography.Org.BouncyCastle.Asn1.X9;
  8. using WCryptography.Org.BouncyCastle.Crypto;
  9. using WCryptography.Org.BouncyCastle.Crypto.Engines;
  10. using WCryptography.Org.BouncyCastle.Crypto.Parameters;
  11. /// <summary>
  12. /// SM2加密
  13. /// </summary>
  14. public class SM2EncryptHelper
  15. {
  16. public static string _publicKeyPem = "";
  17. /// <summary>
  18. /// 初始化公钥
  19. /// </summary>
  20. /// <param name="publicKeyPem"></param>
  21. public static void Init(string publicKeyPem)
  22. {
  23. _publicKeyPem = publicKeyPem;
  24. }
  25. /// <summary>
  26. /// SM2加密,采用C1||C3||C2加密序列,使用SM3算法作为C3的一个坐标及明文的摘要值
  27. /// </summary>
  28. /// <param name="message"></param>
  29. /// <param name="publicKeyPem"></param>
  30. /// <returns>16进制的结果</returns>
  31. public static string Encrypt(string message)
  32. {
  33. try
  34. {
  35. if (string.IsNullOrEmpty(message))
  36. {
  37. throw new ArgumentException("Message cannot be null or empty.", nameof(message));
  38. }
  39. if (string.IsNullOrEmpty(_publicKeyPem))
  40. {
  41. throw new ArgumentException("Public key cannot be null or empty.", nameof(_publicKeyPem));
  42. }
  43. using (StringReader reader = new StringReader(_publicKeyPem))
  44. {
  45. var pemReader = new WCryptography.Org.BouncyCastle.OpenSsl.PemReader(reader);
  46. object obj = pemReader.ReadObject();
  47. if (obj is AsymmetricKeyParameter keyParameter)
  48. {
  49. var q = ((ECPublicKeyParameters)keyParameter).Q;
  50. var x9ec = ECNamedCurveTable.GetByName("sm2p256v1");
  51. var publicParams = new ECPublicKeyParameters(q, new ECDomainParameters(x9ec));
  52. // 创建SM2公钥加密器
  53. var engine = new SM2Engine(SM2Engine.Mode.C1C3C2);
  54. engine.Init(true, publicParams);
  55. // 对消息进行编码
  56. byte[] messageBytes = Encoding.UTF8.GetBytes(message);
  57. byte[] cipherText = engine.ProcessBlock(messageBytes, 0, messageBytes.Length);
  58. // 返回加密后的数据的base64表示
  59. string hexString = BitConverter.ToString(cipherText).Replace("-", "").ToUpper();
  60. return hexString;
  61. }
  62. else
  63. {
  64. throw new ArgumentException("Invalid public key format.", nameof(_publicKeyPem));
  65. }
  66. }
  67. }
  68. catch (Exception ex)
  69. {
  70. Console.WriteLine("Encryption failed: " + ex.Message);
  71. return null;
  72. }
  73. }
  74. }
  75. }