GM.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. // 麻省理工学院许可证
  2. //
  3. // 版权所有 (c) 2021-2023 zuohuaijun,大名科技(天津)有限公司 联系电话/微信:18020030720 QQ:515096995
  4. //
  5. // 特此免费授予获得本软件的任何人以处理本软件的权利,但须遵守以下条件:在所有副本或重要部分的软件中必须包括上述版权声明和本许可声明。
  6. //
  7. // 软件按“原样”提供,不提供任何形式的明示或暗示的保证,包括但不限于对适销性、适用性和非侵权的保证。
  8. // 在任何情况下,作者或版权持有人均不对任何索赔、损害或其他责任负责,无论是因合同、侵权或其他方式引起的,与软件或其使用或其他交易有关。
  9. using Org.BouncyCastle.Asn1;
  10. using Org.BouncyCastle.Asn1.GM;
  11. using Org.BouncyCastle.Asn1.X9;
  12. using Org.BouncyCastle.Crypto;
  13. using Org.BouncyCastle.Crypto.Digests;
  14. using Org.BouncyCastle.Crypto.Engines;
  15. using Org.BouncyCastle.Crypto.Generators;
  16. using Org.BouncyCastle.Crypto.Parameters;
  17. using Org.BouncyCastle.Math;
  18. using Org.BouncyCastle.Security;
  19. using Org.BouncyCastle.Utilities;
  20. using Org.BouncyCastle.Utilities.Encoders;
  21. using Org.BouncyCastle.X509;
  22. namespace Admin.NET.Core;
  23. /**
  24. *
  25. * 用BC的注意点:
  26. * 这个版本的BC对SM3withSM2的结果为asn1格式的r和s,如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
  27. * 这个版本的BC对SM2的结果为C1||C2||C3,据说为旧标准,新标准为C1||C3||C2,用新标准的需要自己转换。下面(被注释掉的)changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2,csharp版没准以后也会加,但目前还没有,java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
  28. *
  29. */
  30. public class GM
  31. {
  32. private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
  33. private static ECDomainParameters ecDomainParameters = new(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
  34. /**
  35. *
  36. * @param msg
  37. * @param userId
  38. * @param privateKey
  39. * @return r||s,直接拼接byte数组的rs
  40. */
  41. public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  42. {
  43. return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
  44. }
  45. /**
  46. * @param msg
  47. * @param userId
  48. * @param privateKey
  49. * @return rs in <b>asn1 format</b>
  50. */
  51. public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  52. {
  53. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  54. signer.Init(true, new ParametersWithID(privateKey, userId));
  55. signer.BlockUpdate(msg, 0, msg.Length);
  56. byte[] sig = signer.GenerateSignature();
  57. return sig;
  58. }
  59. /**
  60. *
  61. * @param msg
  62. * @param userId
  63. * @param rs r||s,直接拼接byte数组的rs
  64. * @param publicKey
  65. * @return
  66. */
  67. public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
  68. {
  69. if (rs == null || msg == null || userId == null) return false;
  70. if (rs.Length != RS_LEN * 2) return false;
  71. return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
  72. }
  73. /**
  74. *
  75. * @param msg
  76. * @param userId
  77. * @param rs in <b>asn1 format</b>
  78. * @param publicKey
  79. * @return
  80. */
  81. public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
  82. {
  83. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  84. signer.Init(false, new ParametersWithID(publicKey, userId));
  85. signer.BlockUpdate(msg, 0, msg.Length);
  86. return signer.VerifySignature(sign);
  87. }
  88. /**
  89. * bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
  90. * @param c1c2c3
  91. * @return
  92. */
  93. private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
  94. {
  95. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  96. const int c3Len = 32; //new SM3Digest().getDigestSize();
  97. byte[] result = new byte[c1c2c3.Length];
  98. Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
  99. Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
  100. Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
  101. return result;
  102. }
  103. /**
  104. * bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
  105. * @param c1c3c2
  106. * @return
  107. */
  108. private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
  109. {
  110. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  111. const int c3Len = 32; //new SM3Digest().GetDigestSize();
  112. byte[] result = new byte[c1c3c2.Length];
  113. Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
  114. Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
  115. Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
  116. return result;
  117. }
  118. /**
  119. * c1||c3||c2
  120. * @param data
  121. * @param key
  122. * @return
  123. */
  124. public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
  125. {
  126. return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
  127. }
  128. /**
  129. * c1||c3||c2
  130. * @param data
  131. * @param key
  132. * @return
  133. */
  134. public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
  135. {
  136. return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
  137. }
  138. /**
  139. * c1||c2||c3
  140. * @param data
  141. * @param key
  142. * @return
  143. */
  144. public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
  145. {
  146. SM2Engine sm2Engine = new SM2Engine();
  147. sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
  148. return sm2Engine.ProcessBlock(data, 0, data.Length);
  149. }
  150. /**
  151. * c1||c2||c3
  152. * @param data
  153. * @param key
  154. * @return
  155. */
  156. public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
  157. {
  158. SM2Engine sm2Engine = new SM2Engine();
  159. sm2Engine.Init(false, key);
  160. return sm2Engine.ProcessBlock(data, 0, data.Length);
  161. }
  162. /**
  163. * @param bytes
  164. * @return
  165. */
  166. public static byte[] Sm3(byte[] bytes)
  167. {
  168. SM3Digest digest = new();
  169. digest.BlockUpdate(bytes, 0, bytes.Length);
  170. byte[] result = DigestUtilities.DoFinal(digest);
  171. return result;
  172. }
  173. private const int RS_LEN = 32;
  174. private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
  175. {
  176. // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
  177. // r and s are the result of mod n, so they should be less than n and have length<=32
  178. byte[] rs = rOrS.ToByteArray();
  179. if (rs.Length == RS_LEN) return rs;
  180. else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
  181. else if (rs.Length < RS_LEN)
  182. {
  183. byte[] result = new byte[RS_LEN];
  184. Arrays.Fill(result, (byte)0);
  185. Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
  186. return result;
  187. }
  188. else
  189. {
  190. throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
  191. }
  192. }
  193. /**
  194. * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
  195. * @param rsDer rs in asn1 format
  196. * @return sign result in plain byte array
  197. */
  198. private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
  199. {
  200. Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
  201. byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
  202. byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
  203. byte[] result = new byte[RS_LEN * 2];
  204. Buffer.BlockCopy(r, 0, result, 0, r.Length);
  205. Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
  206. return result;
  207. }
  208. /**
  209. * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
  210. * @param sign in plain byte array
  211. * @return rs result in asn1 format
  212. */
  213. private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
  214. {
  215. if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
  216. BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
  217. BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
  218. Asn1EncodableVector v = new Asn1EncodableVector
  219. {
  220. new DerInteger(r),
  221. new DerInteger(s)
  222. };
  223. return new DerSequence(v).GetEncoded("DER");
  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 e)
  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. }