GM.cs 16 KB

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