GM.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // 大名科技(天津)有限公司 版权所有
  2. //
  3. // 此源代码遵循位于源代码树根目录中的 LICENSE 文件的许可证
  4. //
  5. // 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动
  6. //
  7. // 任何基于本项目二次开发而产生的一切法律纠纷和责任,均与作者无关
  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.Generators;
  15. using Org.BouncyCastle.Crypto.Parameters;
  16. using Org.BouncyCastle.Math;
  17. using Org.BouncyCastle.Security;
  18. using Org.BouncyCastle.Utilities;
  19. using Org.BouncyCastle.Utilities.Encoders;
  20. using Org.BouncyCastle.X509;
  21. namespace Admin.NET.Core;
  22. /**
  23. *
  24. * 用BC的注意点:
  25. * 这个版本的BC对SM3withSM2的结果为asn1格式的r和s,如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
  26. * 这个版本的BC对SM2的结果为C1||C2||C3,据说为旧标准,新标准为C1||C3||C2,用新标准的需要自己转换。下面(被注释掉的)changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2,csharp版没准以后也会加,但目前还没有,java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
  27. *
  28. */
  29. public class GM
  30. {
  31. private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
  32. private static ECDomainParameters ecDomainParameters = new(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
  33. /**
  34. *
  35. * @param msg
  36. * @param userId
  37. * @param privateKey
  38. * @return r||s,直接拼接byte数组的rs
  39. */
  40. public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  41. {
  42. return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
  43. }
  44. /**
  45. * @param msg
  46. * @param userId
  47. * @param privateKey
  48. * @return rs in <b>asn1 format</b>
  49. */
  50. public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  51. {
  52. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  53. signer.Init(true, new ParametersWithID(privateKey, userId));
  54. signer.BlockUpdate(msg, 0, msg.Length);
  55. byte[] sig = signer.GenerateSignature();
  56. return sig;
  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, AsymmetricKeyParameter publicKey)
  67. {
  68. if (rs == null || msg == null || userId == null) return false;
  69. if (rs.Length != RS_LEN * 2) return false;
  70. return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
  71. }
  72. /**
  73. *
  74. * @param msg
  75. * @param userId
  76. * @param rs in <b>asn1 format</b>
  77. * @param publicKey
  78. * @return
  79. */
  80. public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
  81. {
  82. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  83. signer.Init(false, new ParametersWithID(publicKey, userId));
  84. signer.BlockUpdate(msg, 0, msg.Length);
  85. return signer.VerifySignature(sign);
  86. }
  87. /**
  88. * bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
  89. * @param c1c2c3
  90. * @return
  91. */
  92. private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
  93. {
  94. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  95. const int c3Len = 32; //new SM3Digest().getDigestSize();
  96. byte[] result = new byte[c1c2c3.Length];
  97. Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
  98. Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
  99. Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
  100. return result;
  101. }
  102. /**
  103. * bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
  104. * @param c1c3c2
  105. * @return
  106. */
  107. private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
  108. {
  109. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  110. const int c3Len = 32; //new SM3Digest().GetDigestSize();
  111. byte[] result = new byte[c1c3c2.Length];
  112. Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
  113. Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
  114. Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
  115. return result;
  116. }
  117. /**
  118. * c1||c3||c2
  119. * @param data
  120. * @param key
  121. * @return
  122. */
  123. public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
  124. {
  125. return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
  126. }
  127. /**
  128. * c1||c3||c2
  129. * @param data
  130. * @param key
  131. * @return
  132. */
  133. public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
  134. {
  135. return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
  136. }
  137. /**
  138. * c1||c2||c3
  139. * @param data
  140. * @param key
  141. * @return
  142. */
  143. public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
  144. {
  145. SM2Engine sm2Engine = new SM2Engine();
  146. sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
  147. return sm2Engine.ProcessBlock(data, 0, data.Length);
  148. }
  149. /**
  150. * c1||c2||c3
  151. * @param data
  152. * @param key
  153. * @return
  154. */
  155. public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
  156. {
  157. SM2Engine sm2Engine = new SM2Engine();
  158. sm2Engine.Init(false, key);
  159. return sm2Engine.ProcessBlock(data, 0, data.Length);
  160. }
  161. /**
  162. * @param bytes
  163. * @return
  164. */
  165. public static byte[] Sm3(byte[] bytes)
  166. {
  167. SM3Digest digest = new();
  168. digest.BlockUpdate(bytes, 0, bytes.Length);
  169. byte[] result = DigestUtilities.DoFinal(digest);
  170. return result;
  171. }
  172. private const int RS_LEN = 32;
  173. private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
  174. {
  175. // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
  176. // r and s are the result of mod n, so they should be less than n and have length<=32
  177. byte[] rs = rOrS.ToByteArray();
  178. if (rs.Length == RS_LEN) return rs;
  179. else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
  180. else if (rs.Length < RS_LEN)
  181. {
  182. byte[] result = new byte[RS_LEN];
  183. Arrays.Fill(result, (byte)0);
  184. Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
  185. return result;
  186. }
  187. else
  188. {
  189. throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
  190. }
  191. }
  192. /**
  193. * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
  194. * @param rsDer rs in asn1 format
  195. * @return sign result in plain byte array
  196. */
  197. private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
  198. {
  199. Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
  200. byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
  201. byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
  202. byte[] result = new byte[RS_LEN * 2];
  203. Buffer.BlockCopy(r, 0, result, 0, r.Length);
  204. Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
  205. return result;
  206. }
  207. /**
  208. * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
  209. * @param sign in plain byte array
  210. * @return rs result in asn1 format
  211. */
  212. private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
  213. {
  214. if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
  215. BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
  216. BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
  217. Asn1EncodableVector v = new Asn1EncodableVector
  218. {
  219. new DerInteger(r),
  220. new DerInteger(s)
  221. };
  222. return new DerSequence(v).GetEncoded("DER");
  223. }
  224. // 生成公私匙对
  225. public static AsymmetricCipherKeyPair GenerateKeyPair()
  226. {
  227. ECKeyPairGenerator kpGen = new();
  228. kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
  229. return kpGen.GenerateKeyPair();
  230. }
  231. public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
  232. {
  233. return new ECPrivateKeyParameters(d, ecDomainParameters);
  234. }
  235. public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
  236. {
  237. return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
  238. }
  239. public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
  240. {
  241. FileStream fileStream = null;
  242. try
  243. {
  244. //file.DirectoryName + "\\" + file.Name
  245. fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
  246. X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
  247. return certificate.GetPublicKey();
  248. }
  249. catch (Exception)
  250. {
  251. //log.Error(file.Name + "读取失败,异常:" + e);
  252. }
  253. finally
  254. {
  255. if (fileStream != null)
  256. fileStream.Close();
  257. }
  258. return null;
  259. }
  260. public class Sm2Cert
  261. {
  262. public AsymmetricKeyParameter privateKey;
  263. public AsymmetricKeyParameter publicKey;
  264. public string certId;
  265. }
  266. private static byte[] ToByteArray(int i)
  267. {
  268. byte[] byteArray = new byte[4];
  269. byteArray[0] = (byte)(i >> 24);
  270. byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
  271. byteArray[2] = (byte)((i & 0xFFFF) >> 8);
  272. byteArray[3] = (byte)(i & 0xFF);
  273. return byteArray;
  274. }
  275. /**
  276. * 字节数组拼接
  277. *
  278. * @param params
  279. * @return
  280. */
  281. private static byte[] Join(params byte[][] byteArrays)
  282. {
  283. List<byte> byteSource = new();
  284. for (int i = 0; i < byteArrays.Length; i++)
  285. {
  286. byteSource.AddRange(byteArrays[i]);
  287. }
  288. byte[] data = byteSource.ToArray();
  289. return data;
  290. }
  291. /**
  292. * 密钥派生函数
  293. *
  294. * @param Z
  295. * @param klen
  296. * 生成klen字节数长度的密钥
  297. * @return
  298. */
  299. private static byte[] KDF(byte[] Z, int klen)
  300. {
  301. int ct = 1;
  302. int end = (int)Math.Ceiling(klen * 1.0 / 32);
  303. List<byte> byteSource = new();
  304. for (int i = 1; i < end; i++)
  305. {
  306. byteSource.AddRange(Sm3(Join(Z, ToByteArray(ct))));
  307. ct++;
  308. }
  309. byte[] last = Sm3(Join(Z, ToByteArray(ct)));
  310. if (klen % 32 == 0)
  311. {
  312. byteSource.AddRange(last);
  313. }
  314. else
  315. byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
  316. return byteSource.ToArray();
  317. }
  318. public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, string algo)
  319. {
  320. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  321. if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  322. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  323. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  324. if (iv == null) iv = ZeroIv(algo);
  325. c.Init(false, new ParametersWithIV(key, iv));
  326. return c.DoFinal(cipher);
  327. }
  328. public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, string algo)
  329. {
  330. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  331. if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  332. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  333. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  334. if (iv == null) iv = ZeroIv(algo);
  335. c.Init(true, new ParametersWithIV(key, iv));
  336. return c.DoFinal(plain);
  337. }
  338. public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
  339. {
  340. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  341. //NoPadding 的情况下需要校验数据长度是16的倍数.
  342. if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  343. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  344. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  345. c.Init(true, key);
  346. return c.DoFinal(plain);
  347. }
  348. public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
  349. {
  350. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  351. if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  352. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  353. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  354. c.Init(false, key);
  355. return c.DoFinal(cipher);
  356. }
  357. public const string SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
  358. public const string SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
  359. public const string SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
  360. /**
  361. * cfca官网CSP沙箱导出的sm2文件
  362. * @param pem 二进制原文
  363. * @param pwd 密码
  364. * @return
  365. */
  366. public static Sm2Cert ReadSm2File(byte[] pem, string pwd)
  367. {
  368. Sm2Cert sm2Cert = new();
  369. Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
  370. // ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
  371. Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
  372. Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert
  373. // ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
  374. // ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
  375. Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
  376. byte[] key = KDF(System.Text.Encoding.UTF8.GetBytes(pwd), 32);
  377. byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
  378. priKeyAsn1.GetOctets(),
  379. Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
  380. sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
  381. // log.Info(Hex.toHexString(priKeyD));
  382. // ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
  383. Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
  384. X509Certificate x509 = new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
  385. sm2Cert.publicKey = x509.GetPublicKey();
  386. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进制,有啥其他进制要求的自己改改
  387. return sm2Cert;
  388. }
  389. /**
  390. *
  391. * @param cert
  392. * @return
  393. */
  394. public static Sm2Cert ReadSm2X509Cert(byte[] cert)
  395. {
  396. Sm2Cert sm2Cert = new();
  397. X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
  398. sm2Cert.publicKey = x509.GetPublicKey();
  399. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进制,有啥其他进制要求的自己改改
  400. return sm2Cert;
  401. }
  402. public static byte[] ZeroIv(string algo)
  403. {
  404. IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
  405. int blockSize = cipher.GetBlockSize();
  406. byte[] iv = new byte[blockSize];
  407. Arrays.Fill(iv, (byte)0);
  408. return iv;
  409. }
  410. }