平安校园
25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

SM2CryptoUtil.cs 12 KiB

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