GM.cs 16 KB

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