EasyGmUtils.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. /*
  2. * @Description:
  3. * @Author: ylz-lichong
  4. * @Date: 2022-06-16 17:46:23
  5. */
  6. using System;
  7. using Org.BouncyCastle.Utilities.Encoders;
  8. using Org.BouncyCastle.Asn1;
  9. using Org.BouncyCastle.Asn1.GM;
  10. using Org.BouncyCastle.Asn1.X9;
  11. using Org.BouncyCastle.Crypto;
  12. using Org.BouncyCastle.Crypto.Digests;
  13. using Org.BouncyCastle.Crypto.Engines;
  14. using Org.BouncyCastle.Crypto.Parameters;
  15. using Org.BouncyCastle.Math;
  16. using Org.BouncyCastle.Security;
  17. using Org.BouncyCastle.Utilities;
  18. using System.IO;
  19. namespace SM2Crypto.Lib
  20. {
  21. class EasyGmUtils
  22. {
  23. private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
  24. private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
  25. /**
  26. *
  27. * @param msg
  28. * @param userId
  29. * @param privateKey
  30. * @return r||s,直接拼接byte数组的rs
  31. */
  32. public static byte[] signSm3WithSm2(byte[] msg, byte[] userId, byte[] privateKeyBytes)
  33. {
  34. ECPrivateKeyParameters privateKeyParameters=getPrivatekeyFromD(new BigInteger(1, privateKeyBytes));
  35. return rsAsn1ToPlainByteArray(signSm3WithSm2Asn1Rs(msg, userId, privateKeyParameters));
  36. }
  37. /**
  38. * @param msg
  39. * @param userId
  40. * @param privateKey
  41. * @return rs in <b>asn1 format</b>
  42. */
  43. public static byte[] signSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  44. {
  45. try
  46. {
  47. ISigner signer = SignerUtilities.InitSigner("SM3withSM2", true, privateKey, new SecureRandom());
  48. signer.BlockUpdate(msg, 0, msg.Length);
  49. byte[] sig = signer.GenerateSignature();
  50. return sig;
  51. }
  52. catch (Exception e)
  53. {
  54. //log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
  55. return null;
  56. }
  57. }
  58. /**
  59. *
  60. * @param msg
  61. * @param userId
  62. * @param rs r||s,直接拼接byte数组的rs
  63. * @param publicKey
  64. * @return
  65. */
  66. public static bool verifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, byte[] publicKeyBytes)
  67. {
  68. if (rs == null || msg == null || userId == null) return false;
  69. if (rs.Length != RS_LEN * 2) return false;
  70. if (publicKeyBytes.Length != 64 && publicKeyBytes.Length != 65) throw new ArgumentException("err key length");
  71. BigInteger x, y;
  72. if (publicKeyBytes.Length > 64)
  73. {
  74. x = fromUnsignedByteArray(publicKeyBytes, 1, 32);
  75. y = fromUnsignedByteArray(publicKeyBytes, 33, 32);
  76. }
  77. else
  78. {
  79. x = fromUnsignedByteArray(publicKeyBytes, 0, 32);
  80. y = fromUnsignedByteArray(publicKeyBytes, 32, 32);
  81. }
  82. ECPublicKeyParameters publicKey = getPublickeyFromXY(x, y);
  83. return verifySm3WithSm2Asn1Rs(msg, userId, rsPlainByteArrayToAsn1(rs), publicKey);
  84. }
  85. public static BigInteger fromUnsignedByteArray(byte[] var0, int var1, int var2)
  86. {
  87. byte[] var3 = var0;
  88. if (var1 != 0 || var2 != var0.Length)
  89. {
  90. var3 = new byte[var2];
  91. Array.Copy(var0, var1, var3, 0, var2);
  92. }
  93. return new BigInteger(1, var3);
  94. }
  95. /**
  96. *
  97. * @param msg
  98. * @param userId
  99. * @param rs in <b>asn1 format</b>
  100. * @param publicKey
  101. * @return
  102. */
  103. public static bool verifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
  104. {
  105. try
  106. {
  107. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  108. signer.Init(false, publicKey);
  109. signer.BlockUpdate(msg, 0, msg.Length);
  110. return signer.VerifySignature(sign);
  111. }
  112. catch (Exception e)
  113. {
  114. //log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
  115. return false;
  116. }
  117. }
  118. /**
  119. * bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
  120. * @param c1c2c3
  121. * @return
  122. */
  123. private static byte[] changeC1C2C3ToC1C3C2(byte[] c1c2c3)
  124. {
  125. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  126. const int c3Len = 32; //new SM3Digest().getDigestSize();
  127. byte[] result = new byte[c1c2c3.Length];
  128. Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
  129. Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
  130. Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
  131. return result;
  132. }
  133. /**
  134. * bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
  135. * @param c1c3c2
  136. * @return
  137. */
  138. private static byte[] changeC1C3C2ToC1C2C3(byte[] c1c3c2)
  139. {
  140. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  141. const int c3Len = 32; //new SM3Digest().GetDigestSize();
  142. byte[] result = new byte[c1c3c2.Length];
  143. Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
  144. Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
  145. Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
  146. return result;
  147. }
  148. /**
  149. * c1||c3||c2
  150. * @param data
  151. * @param key
  152. * @return
  153. */
  154. public static byte[] sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
  155. {
  156. return sm2DecryptOld(changeC1C3C2ToC1C2C3(data), key);
  157. }
  158. /**
  159. * c1||c3||c2
  160. * @param data
  161. * @param key
  162. * @return
  163. */
  164. public static byte[] sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
  165. {
  166. return changeC1C2C3ToC1C3C2(sm2EncryptOld(data, key));
  167. }
  168. /**
  169. * c1||c2||c3
  170. * @param data
  171. * @param key
  172. * @return
  173. */
  174. public static byte[] sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
  175. {
  176. try
  177. {
  178. SM2Engine sm2Engine = new SM2Engine();
  179. sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
  180. return sm2Engine.ProcessBlock(data, 0, data.Length);
  181. }
  182. catch (Exception e)
  183. {
  184. //log.Error("Sm2EncryptOld error: " + e.Message, e);
  185. return null;
  186. }
  187. }
  188. /**
  189. * c1||c2||c3
  190. * @param data
  191. * @param key
  192. * @return
  193. */
  194. public static byte[] sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
  195. {
  196. try
  197. {
  198. SM2Engine sm2Engine = new SM2Engine();
  199. sm2Engine.Init(false, key);
  200. return sm2Engine.ProcessBlock(data, 0, data.Length);
  201. }
  202. catch (Exception e)
  203. {
  204. //log.Error("Sm2DecryptOld error: " + e.Message, e);
  205. return null;
  206. }
  207. }
  208. /**
  209. * @param bytes
  210. * @return
  211. */
  212. public static byte[] sm3(byte[] bytes)
  213. {
  214. try
  215. {
  216. SM3Digest digest = new SM3Digest();
  217. digest.BlockUpdate(bytes, 0, bytes.Length);
  218. byte[] result = DigestUtilities.DoFinal(digest);
  219. return result;
  220. }
  221. catch (Exception e)
  222. {
  223. //log.Error("Sm3 error: " + e.Message, e);
  224. return null;
  225. }
  226. }
  227. private const int RS_LEN = 32;
  228. private static byte[] bigIntToFixexLengthBytes(BigInteger rOrS)
  229. {
  230. // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
  231. // r and s are the result of mod n, so they should be less than n and have length<=32
  232. byte[] rs = rOrS.ToByteArray();
  233. if (rs.Length == RS_LEN) return rs;
  234. else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
  235. else if (rs.Length < RS_LEN)
  236. {
  237. byte[] result = new byte[RS_LEN];
  238. Arrays.Fill(result, (byte)0);
  239. Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
  240. return result;
  241. }
  242. else
  243. {
  244. throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
  245. }
  246. }
  247. /**
  248. * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
  249. * @param rsDer rs in asn1 format
  250. * @return sign result in plain byte array
  251. */
  252. private static byte[] rsAsn1ToPlainByteArray(byte[] rsDer)
  253. {
  254. Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
  255. byte[] r = bigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
  256. byte[] s = bigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
  257. byte[] result = new byte[RS_LEN * 2];
  258. Buffer.BlockCopy(r, 0, result, 0, r.Length);
  259. Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
  260. return result;
  261. }
  262. /**
  263. * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
  264. * @param sign in plain byte array
  265. * @return rs result in asn1 format
  266. */
  267. private static byte[] rsPlainByteArrayToAsn1(byte[] sign)
  268. {
  269. if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
  270. BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
  271. BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
  272. Asn1EncodableVector v = new Asn1EncodableVector();
  273. v.Add(new DerInteger(r));
  274. v.Add(new DerInteger(s));
  275. try
  276. {
  277. return new DerSequence(v).GetEncoded("DER");
  278. }
  279. catch (IOException e)
  280. {
  281. //log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
  282. return null;
  283. }
  284. }
  285. public static byte[] sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, String algo)
  286. {
  287. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  288. if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
  289. try
  290. {
  291. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  292. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  293. if (iv == null) iv = zeroIv(algo);
  294. c.Init(false, new ParametersWithIV(key, iv));
  295. return c.DoFinal(cipher);
  296. }
  297. catch (Exception e)
  298. {
  299. //log.Error("Sm4DecryptCBC error: " + e.Message, e);
  300. return null;
  301. }
  302. }
  303. public static byte[] sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, String algo)
  304. {
  305. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  306. if (plain.Length % 16 != 0) throw new ArgumentException("err data length");
  307. try
  308. {
  309. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  310. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  311. if (iv == null) iv = zeroIv(algo);
  312. c.Init(true, new ParametersWithIV(key, iv));
  313. return c.DoFinal(plain);
  314. }
  315. catch (Exception e)
  316. {
  317. //log.Error("Sm4EncryptCBC error: " + e.Message, e);
  318. return null;
  319. }
  320. }
  321. public static byte[] sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
  322. {
  323. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  324. if (plain.Length % 16 != 0) throw new ArgumentException("err data length");
  325. try
  326. {
  327. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  328. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  329. c.Init(true, key);
  330. return c.DoFinal(plain);
  331. }
  332. catch (Exception e)
  333. {
  334. //log.Error("Sm4EncryptECB error: " + e.Message, e);
  335. return null;
  336. }
  337. }
  338. public static byte[] sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
  339. {
  340. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  341. if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
  342. try
  343. {
  344. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  345. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  346. c.Init(false, key);
  347. return c.DoFinal(cipher);
  348. }
  349. catch (Exception e)
  350. {
  351. //log.Error("Sm4DecryptECB error: " + e.Message, e);
  352. return null;
  353. }
  354. }
  355. public static ECPrivateKeyParameters getPrivatekeyFromD(BigInteger d)
  356. {
  357. return new ECPrivateKeyParameters(d, ecDomainParameters);
  358. }
  359. public static ECPublicKeyParameters getPublickeyFromXY(BigInteger x, BigInteger y)
  360. {
  361. return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
  362. }
  363. public static byte[] sm4Encrypt(byte[] keyBytes, byte[] plain)
  364. {
  365. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  366. // if (plain.length % 16 != 0) throw new RuntimeException("err data length");
  367. try
  368. {
  369. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  370. IBufferedCipher c = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
  371. c.Init(true, key);
  372. return c.DoFinal(plain);
  373. }
  374. catch (Exception e)
  375. {
  376. return null;
  377. }
  378. }
  379. public static byte[] sm4Decrypt(byte[] keyBytes, byte[] cipher)
  380. {
  381. // if (keyBytes.length != 16) throw new RuntimeException("err key length");
  382. if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
  383. try
  384. {
  385. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  386. IBufferedCipher c = CipherUtilities.GetCipher("SM4/ECB/PKCS7Padding");
  387. c.Init(false, key);
  388. return c.DoFinal(cipher);
  389. }
  390. catch (Exception e)
  391. {
  392. return null;
  393. }
  394. }
  395. public const String SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
  396. public const String SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
  397. public const String SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
  398. public static byte[] zeroIv(String algo)
  399. {
  400. try
  401. {
  402. IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
  403. int blockSize = cipher.GetBlockSize();
  404. byte[] iv = new byte[blockSize];
  405. Arrays.Fill(iv, (byte)0);
  406. return iv;
  407. }
  408. catch (Exception e)
  409. {
  410. //log.Error("ZeroIv error: " + e.Message, e);
  411. return null;
  412. }
  413. }
  414. }
  415. }