Nessuna descrizione

SM2CryptoUtil.cs 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Crypto.Digests;
  3. using Org.BouncyCastle.Crypto.Generators;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Math;
  6. using Org.BouncyCastle.Math.EC;
  7. using Org.BouncyCastle.Security;
  8. using Org.BouncyCastle.Utilities.Encoders;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Linq;
  13. using System.Text;
  14. namespace CallCenter.Utility
  15. {
  16. /// <summary>
  17. /// SM2工具类
  18. /// </summary>
  19. public class SM2CryptoUtil
  20. {
  21. #region 获取公钥私钥
  22. /// <summary>
  23. /// 获取公钥私钥
  24. /// </summary>
  25. /// <returns></returns>
  26. public static SM2Model GetKey()
  27. {
  28. SM2 sm2 = SM2.Instance;
  29. AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
  30. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
  31. ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
  32. BigInteger privateKey = ecpriv.D;
  33. ECPoint publicKey = ecpub.Q;
  34. SM2Model sM2Model = new SM2Model();
  35. sM2Model.PrivateKey = Encoding.UTF8.GetString(Hex.Encode(privateKey.ToByteArray())).ToUpper();
  36. sM2Model.PublicKey = Encoding.UTF8.GetString(Hex.Encode(publicKey.GetEncoded())).ToUpper();
  37. return sM2Model;
  38. }
  39. #endregion
  40. #region 加密
  41. /// <summary>
  42. /// 加密
  43. /// </summary>
  44. /// <param name="publickey">公钥</param>
  45. /// <param name="sourceData">需要加密的值</param>
  46. /// <returns>加密结果</returns>
  47. public static string Encrypt(string publickey, string sourceData)
  48. {
  49. var data = Encrypt(Hex.Decode(publickey), Encoding.UTF8.GetBytes(sourceData));
  50. return data;
  51. }
  52. /// <summary>
  53. /// 加密
  54. /// </summary>
  55. /// <param name="publicKey">公钥</param>
  56. /// <param name="data">需要加密的值</param>
  57. /// <returns></returns>
  58. public static String Encrypt(byte[] publicKey, byte[] data)
  59. {
  60. if (null == publicKey || publicKey.Length == 0)
  61. {
  62. return null;
  63. }
  64. if (data == null || data.Length == 0)
  65. {
  66. return null;
  67. }
  68. byte[] source = new byte[data.Length];
  69. Array.Copy(data, 0, source, 0, data.Length);
  70. Cipher cipher = new Cipher();
  71. SM2 sm2 = SM2.Instance;
  72. ECPoint userKey = sm2.ecc_curve.DecodePoint(publicKey);
  73. ECPoint c1 = cipher.Init_enc(sm2, userKey);
  74. cipher.Encrypt(source);
  75. byte[] c3 = new byte[32];
  76. cipher.Dofinal(c3);
  77. String sc1 = Encoding.UTF8.GetString(Hex.Encode(c1.GetEncoded()));
  78. String sc2 = Encoding.UTF8.GetString(Hex.Encode(source));
  79. String sc3 = Encoding.UTF8.GetString(Hex.Encode(c3));
  80. return (sc1 + sc2 + sc3).ToUpper();
  81. }
  82. #endregion
  83. #region 解密
  84. /// <summary>
  85. ///
  86. /// </summary>
  87. /// <param name="privateKey"></param>
  88. /// <param name="encryptedData"></param>
  89. /// <returns></returns>
  90. public static string Decrypt(string privateKey, string encryptedData)
  91. {
  92. var data = Encoding.UTF8.GetString(Decrypt(Hex.Decode(privateKey), Hex.Decode(encryptedData)));
  93. return data;
  94. }
  95. /// <summary>
  96. /// 解密
  97. /// </summary>
  98. /// <param name="privateKey"></param>
  99. /// <param name="encryptedData"></param>
  100. /// <returns></returns>
  101. public static byte[] Decrypt(byte[] privateKey, byte[] encryptedData)
  102. {
  103. if (null == privateKey || privateKey.Length == 0)
  104. {
  105. return null;
  106. }
  107. if (encryptedData == null || encryptedData.Length == 0)
  108. {
  109. return null;
  110. }
  111. String data = Encoding.UTF8.GetString(Hex.Encode(encryptedData));
  112. byte[] c1Bytes = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(0, 130)));
  113. int c2Len = encryptedData.Length - 97;
  114. byte[] c2 = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(130, 2 * c2Len)));
  115. byte[] c3 = Hex.Decode(Encoding.UTF8.GetBytes(data.Substring(130 + 2 * c2Len, 64)));
  116. SM2 sm2 = SM2.Instance;
  117. BigInteger userD = new BigInteger(1, privateKey);
  118. //ECPoint c1 = sm2.ecc_curve.DecodePoint(c1Bytes);
  119. ECPoint c1 = sm2.ecc_curve.DecodePoint(c1Bytes);
  120. Cipher cipher = new Cipher();
  121. cipher.Init_dec(userD, c1);
  122. cipher.Decrypt(c2);
  123. cipher.Dofinal(c3);
  124. return c2;
  125. }
  126. #endregion
  127. private class Cipher
  128. {
  129. private int ct;
  130. private ECPoint p2;
  131. private SM3Digest sm3keybase;
  132. private SM3Digest sm3c3;
  133. private byte[] key;
  134. private byte keyOff;
  135. public Cipher()
  136. {
  137. this.ct = 1;
  138. this.key = new byte[32];
  139. this.keyOff = 0;
  140. }
  141. public static byte[] byteConvert32Bytes(BigInteger n)
  142. {
  143. byte[] tmpd = null;
  144. if (n == null)
  145. {
  146. return null;
  147. }
  148. if (n.ToByteArray().Length == 33)
  149. {
  150. tmpd = new byte[32];
  151. Array.Copy(n.ToByteArray(), 1, tmpd, 0, 32);
  152. }
  153. else if (n.ToByteArray().Length == 32)
  154. {
  155. tmpd = n.ToByteArray();
  156. }
  157. else
  158. {
  159. tmpd = new byte[32];
  160. for (int i = 0; i < 32 - n.ToByteArray().Length; i++)
  161. {
  162. tmpd[i] = 0;
  163. }
  164. Array.Copy(n.ToByteArray(), 0, tmpd, 32 - n.ToByteArray().Length, n.ToByteArray().Length);
  165. }
  166. return tmpd;
  167. }
  168. private void Reset()
  169. {
  170. this.sm3keybase = new SM3Digest();
  171. this.sm3c3 = new SM3Digest();
  172. byte[] p = byteConvert32Bytes(p2.Normalize().XCoord.ToBigInteger());
  173. this.sm3keybase.BlockUpdate(p, 0, p.Length);
  174. this.sm3c3.BlockUpdate(p, 0, p.Length);
  175. p = byteConvert32Bytes(p2.Normalize().YCoord.ToBigInteger());
  176. this.sm3keybase.BlockUpdate(p, 0, p.Length);
  177. this.ct = 1;
  178. NextKey();
  179. }
  180. private void NextKey()
  181. {
  182. SM3Digest sm3keycur = new SM3Digest(this.sm3keybase);
  183. sm3keycur.Update((byte)(ct >> 24 & 0xff));
  184. sm3keycur.Update((byte)(ct >> 16 & 0xff));
  185. sm3keycur.Update((byte)(ct >> 8 & 0xff));
  186. sm3keycur.Update((byte)(ct & 0xff));
  187. sm3keycur.DoFinal(key, 0);
  188. this.keyOff = 0;
  189. this.ct++;
  190. }
  191. public ECPoint Init_enc(SM2 sm2, ECPoint userKey)
  192. {
  193. AsymmetricCipherKeyPair key = sm2.ecc_key_pair_generator.GenerateKeyPair();
  194. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
  195. ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
  196. BigInteger k = ecpriv.D;
  197. ECPoint c1 = ecpub.Q;
  198. this.p2 = userKey.Multiply(k);
  199. Reset();
  200. return c1;
  201. }
  202. public void Encrypt(byte[] data)
  203. {
  204. this.sm3c3.BlockUpdate(data, 0, data.Length);
  205. for (int i = 0; i < data.Length; i++)
  206. {
  207. if (keyOff == key.Length)
  208. {
  209. NextKey();
  210. }
  211. data[i] ^= key[keyOff++];
  212. }
  213. }
  214. public void Init_dec(BigInteger userD, ECPoint c1)
  215. {
  216. this.p2 = c1.Multiply(userD);
  217. Reset();
  218. }
  219. public void Decrypt(byte[] data)
  220. {
  221. for (int i = 0; i < data.Length; i++)
  222. {
  223. if (keyOff == key.Length)
  224. {
  225. NextKey();
  226. }
  227. data[i] ^= key[keyOff++];
  228. }
  229. this.sm3c3.BlockUpdate(data, 0, data.Length);
  230. }
  231. public void Dofinal(byte[] c3)
  232. {
  233. byte[] p = byteConvert32Bytes(p2.Normalize().YCoord.ToBigInteger());
  234. this.sm3c3.BlockUpdate(p, 0, p.Length);
  235. this.sm3c3.DoFinal(c3, 0);
  236. Reset();
  237. }
  238. }
  239. private class SM2
  240. {
  241. public static SM2 Instance
  242. {
  243. get
  244. {
  245. return new SM2();
  246. }
  247. }
  248. public static SM2 InstanceTest
  249. {
  250. get
  251. {
  252. return new SM2();
  253. }
  254. }
  255. public static readonly string[] sm2_param = {
  256. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",// p,0
  257. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",// a,1
  258. "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",// b,2
  259. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",// n,3
  260. "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",// gx,4
  261. "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0" // gy,5
  262. };
  263. public string[] ecc_param = sm2_param;
  264. public readonly BigInteger ecc_p;
  265. public readonly BigInteger ecc_a;
  266. public readonly BigInteger ecc_b;
  267. public readonly BigInteger ecc_n;
  268. public readonly BigInteger ecc_gx;
  269. public readonly BigInteger ecc_gy;
  270. public readonly ECCurve ecc_curve;
  271. public readonly ECPoint ecc_point_g;
  272. public readonly ECDomainParameters ecc_bc_spec;
  273. public readonly ECKeyPairGenerator ecc_key_pair_generator;
  274. private SM2()
  275. {
  276. ecc_param = sm2_param;
  277. ECFieldElement ecc_gx_fieldelement;
  278. ECFieldElement ecc_gy_fieldelement;
  279. ecc_p = new BigInteger(ecc_param[0], 16);
  280. ecc_a = new BigInteger(ecc_param[1], 16);
  281. ecc_b = new BigInteger(ecc_param[2], 16);
  282. ecc_n = new BigInteger(ecc_param[3], 16);
  283. ecc_gx = new BigInteger(ecc_param[4], 16);
  284. ecc_gy = new BigInteger(ecc_param[5], 16);
  285. ecc_gx_fieldelement = new FpFieldElement(ecc_p, ecc_gx);
  286. ecc_gy_fieldelement = new FpFieldElement(ecc_p, ecc_gy);
  287. ecc_curve = new FpCurve(ecc_p, ecc_a, ecc_b);
  288. ecc_point_g = new FpPoint(ecc_curve, ecc_gx_fieldelement, ecc_gy_fieldelement);
  289. ecc_bc_spec = new ECDomainParameters(ecc_curve, ecc_point_g, ecc_n);
  290. ECKeyGenerationParameters ecc_ecgenparam;
  291. ecc_ecgenparam = new ECKeyGenerationParameters(ecc_bc_spec, new SecureRandom());
  292. ecc_key_pair_generator = new ECKeyPairGenerator();
  293. ecc_key_pair_generator.Init(ecc_ecgenparam);
  294. }
  295. public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey)
  296. {
  297. SM3Digest sm3 = new SM3Digest();
  298. byte[] p;
  299. // userId length
  300. int len = userId.Length * 8;
  301. sm3.Update((byte)(len >> 8 & 0x00ff));
  302. sm3.Update((byte)(len & 0x00ff));
  303. // userId
  304. sm3.BlockUpdate(userId, 0, userId.Length);
  305. // a,b
  306. p = ecc_a.ToByteArray();
  307. sm3.BlockUpdate(p, 0, p.Length);
  308. p = ecc_b.ToByteArray();
  309. sm3.BlockUpdate(p, 0, p.Length);
  310. // gx,gy
  311. p = ecc_gx.ToByteArray();
  312. sm3.BlockUpdate(p, 0, p.Length);
  313. p = ecc_gy.ToByteArray();
  314. sm3.BlockUpdate(p, 0, p.Length);
  315. // x,y
  316. p = userKey.AffineXCoord.ToBigInteger().ToByteArray();
  317. sm3.BlockUpdate(p, 0, p.Length);
  318. p = userKey.AffineYCoord.ToBigInteger().ToByteArray();
  319. sm3.BlockUpdate(p, 0, p.Length);
  320. // Z
  321. byte[] md = new byte[sm3.GetDigestSize()];
  322. sm3.DoFinal(md, 0);
  323. return md;
  324. }
  325. }
  326. public class SM2Model
  327. {
  328. /// <summary>
  329. /// 公钥
  330. /// </summary>
  331. public string PublicKey { get; set; }
  332. /// <summary>
  333. /// 私钥
  334. /// </summary>
  335. public string PrivateKey { get; set; }
  336. }
  337. /// <summary>
  338. /// 公钥
  339. /// </summary>
  340. public static string PublicKey = "042DBA45E7B03394F603CADAFCDDEC854D3E01A4E9C52CD799B85B1A14BDB970137AE58BA" +
  341. "553D79F058604DC1CD4B77DE5408BA3308E767584100C2B663510C819";
  342. /// <summary>
  343. /// 私钥
  344. /// </summary>
  345. public static string PrivateKey = "BF1F907B4E0487F798DC80AFD7BC2A6201E8514233002272EA3BE2FC6F797843";
  346. /// <summary>
  347. /// 公钥加密明文
  348. /// </summary>
  349. /// <param name="plainText">明文</param>
  350. /// <returns>密文</returns>
  351. public static string Encrypt(string plainText)
  352. {
  353. return Encrypt(PublicKey, plainText);
  354. }
  355. /// <summary>
  356. /// SM2私钥解密密文
  357. /// </summary>
  358. /// <param name="cipherText">密文</param>
  359. /// <returns>明文</returns>
  360. public static string Decrypt(string cipherText)
  361. {
  362. if (!cipherText.StartsWith("04")) cipherText = "04" + cipherText;//
  363. return Decrypt(PrivateKey, cipherText);
  364. }
  365. }
  366. }