sm3withsm2.cs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. namespace OASystem.API.CMBPayBusiness
  2. {
  3. /**
  4. * need lib:
  5. * BouncyCastle.Crypto.dll(http://www.bouncycastle.org/csharp/index.html)(这段代码写的时候用的bccrypto-csharp-1.8.8,最低支持版本和最高支持版本自己研究)
  6. * log4net.dll(http://logging.apache.org/log4net/)(仅为了输出日志用,不用的话可自行改换其他方式输出异常信息)
  7. *
  8. * ref:
  9. * https://tools.ietf.org/html/draft-shen-sm2-ecdsa-02
  10. * http://gmssl.org/docs/oid.html
  11. * http://www.jonllen.com/jonllen/work/164.aspx
  12. *
  13. * 用BC的注意点:
  14. * 这个版本的BC对SM3withSM2的结果为asn1格式的r和s,如果需要直接拼接的r||s需要自己转换。下面rsAsn1ToPlainByteArray、rsPlainByteArrayToAsn1就在干这事。
  15. * 这个版本的BC对SM2的结果为C1||C2||C3,据说为旧标准,新标准为C1||C3||C2,用新标准的需要自己转换。下面(被注释掉的)changeC1C2C3ToC1C3C2、changeC1C3C2ToC1C2C3就在干这事。java版的高版本有加上C1C3C2,csharp版没准以后也会加,但目前还没有,java版的目前可以初始化时“ SM2Engine sm2Engine = new SM2Engine(SM2Engine.Mode.C1C3C2);”。
  16. *
  17. */
  18. public class GmUtil
  19. {
  20. private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
  21. private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
  22. //国密标准公钥头(固定值)
  23. public const string SM2_KEY_TITLE = "3059301306072a8648ce3d020106082a811ccf5501822d03420004";
  24. //国密局推荐 ID(固定值)
  25. public const string SM_USER_ID = "1234567812345678";
  26. //国密私钥
  27. public const string SM_PRIVATE_KEY = "D5F2AFA24E6BA9071B54A8C9AD735F9A1DE9C4657FA386C09B592694BC118B38";
  28. //国密公钥 base64
  29. public const string SM_PUBLIC_KEY = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE6Q+fktsnY9OFP+LpSR5Udbxf5zHCFO0PmOKlFNTxDIGl8jsPbbB/9ET23NV+acSz4FEkzD74sW2iiNVHRLiKHg==";
  30. /**
  31. *
  32. * @param msg
  33. * @param userId
  34. * @param privateKey
  35. * @return r||s,直接拼接byte数组的rs
  36. */
  37. public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  38. {
  39. return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
  40. }
  41. /**
  42. * 将BC SM2 RAW签名值转化为ASN1格式签名值
  43. * @param bcCipTxt
  44. * @return
  45. * @throws Exception
  46. */
  47. private static byte[] signRawToAsn1(byte[] bcCipTxt)
  48. {
  49. byte[] netSignCipTxt = new byte[73];
  50. byte[] signR = new byte[32];
  51. byte[] signS = new byte[32];
  52. Buffer.BlockCopy(bcCipTxt, 0, signR, 0, 32);
  53. Buffer.BlockCopy(bcCipTxt, 32, signS, 0, 32);
  54. //signR补位
  55. int wPos = 4;
  56. netSignCipTxt[0] = 0x30;
  57. netSignCipTxt[2] = 0x02;
  58. if ((signR[0] & 0xFF) >= 128)
  59. {
  60. netSignCipTxt[wPos - 1] = 0x21;
  61. netSignCipTxt[wPos] = 0x00;
  62. wPos += 1;
  63. }
  64. else
  65. {
  66. netSignCipTxt[wPos - 1] = 0x20;
  67. }
  68. Buffer.BlockCopy(signR, 0, netSignCipTxt, wPos, 32);
  69. wPos += 32;
  70. //signS补位
  71. netSignCipTxt[wPos] = 0x02;
  72. wPos += 1;
  73. if ((signS[0] & 0xFF) >= 128)
  74. {
  75. netSignCipTxt[wPos] = 0x21;
  76. wPos += 1;
  77. netSignCipTxt[wPos] = 0x00;
  78. wPos += 1;
  79. }
  80. else
  81. {
  82. netSignCipTxt[wPos] = 0x20;
  83. wPos += 1;
  84. }
  85. Buffer.BlockCopy(signS, 0, netSignCipTxt, wPos, 32);
  86. wPos += 32;
  87. if (70 == wPos)
  88. {
  89. netSignCipTxt[1] = 0x44;
  90. }
  91. else if (71 == wPos)
  92. {
  93. netSignCipTxt[1] = 0x45;
  94. }
  95. else if (72 == wPos)
  96. {
  97. netSignCipTxt[1] = 0x46;
  98. }
  99. else
  100. {
  101. throw new Exception("signRawToAsn1 Error!");
  102. }
  103. byte[] resultBytes = new byte[wPos];
  104. Buffer.BlockCopy(netSignCipTxt, 0, resultBytes, 0, wPos);
  105. return resultBytes;
  106. }
  107. /**
  108. * 将ASN1格式签名值转化为BC SM2 RAW 签名值
  109. *
  110. * @param signature Asn1格式签名值
  111. * @return byte[] Raw签名值
  112. */
  113. private static byte[] signAsn12Raw(byte[] signature)
  114. {
  115. byte[] resultBytes = new byte[64];
  116. //截取signR
  117. int wPos = 3;
  118. if ((signature[wPos] & 0xFF) == 32)
  119. {
  120. wPos += 1;
  121. }
  122. else if ((signature[wPos] & 0xFF) == 33)
  123. {
  124. wPos += 2;
  125. }
  126. else
  127. {
  128. throw new Exception("signR length Error!");
  129. }
  130. Buffer.BlockCopy(signature, wPos, resultBytes, 0, 32);
  131. wPos += 32;
  132. //截取signS
  133. wPos += 1;
  134. if ((signature[wPos] & 0xFF) == 32)
  135. {
  136. wPos += 1;
  137. }
  138. else if ((signature[wPos] & 0xFF) == 33)
  139. {
  140. wPos += 2;
  141. }
  142. else
  143. {
  144. throw new Exception("signS length Error!");
  145. }
  146. Buffer.BlockCopy(signature, wPos, resultBytes, 32, 32);
  147. return resultBytes;
  148. }
  149. /**
  150. * @param msg
  151. * @param userId
  152. * @param privateKey
  153. * @return rs in <b>asn1 format</b>
  154. */
  155. public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  156. {
  157. try
  158. {
  159. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  160. signer.Init(true, new ParametersWithID(privateKey, userId));
  161. signer.BlockUpdate(msg, 0, msg.Length);
  162. byte[] sig = signer.GenerateSignature();
  163. return sig;
  164. }
  165. catch (Exception e)
  166. {
  167. ////log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
  168. return null;
  169. }
  170. }
  171. /**
  172. *
  173. * @param msg
  174. * @param userId
  175. * @param rs r||s,直接拼接byte数组的rs
  176. * @param publicKey
  177. * @return
  178. */
  179. public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
  180. {
  181. if (rs == null || msg == null || userId == null) return false;
  182. if (rs.Length != RS_LEN * 2) return false;
  183. return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
  184. }
  185. /**
  186. *
  187. * @param msg
  188. * @param userId
  189. * @param rs in <b>asn1 format</b>
  190. * @param publicKey
  191. * @return
  192. */
  193. public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
  194. {
  195. try
  196. {
  197. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  198. signer.Init(false, new ParametersWithID(publicKey, userId));
  199. signer.BlockUpdate(msg, 0, msg.Length);
  200. return signer.VerifySignature(sign);
  201. }
  202. catch (Exception e)
  203. {
  204. ////log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
  205. return false;
  206. }
  207. }
  208. /**
  209. * bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
  210. * @param c1c2c3
  211. * @return
  212. */
  213. private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
  214. {
  215. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  216. const int c3Len = 32; //new SM3Digest().getDigestSize();
  217. byte[] result = new byte[c1c2c3.Length];
  218. Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
  219. Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
  220. Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
  221. return result;
  222. }
  223. /**
  224. * bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
  225. * @param c1c3c2
  226. * @return
  227. */
  228. private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
  229. {
  230. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  231. const int c3Len = 32; //new SM3Digest().GetDigestSize();
  232. byte[] result = new byte[c1c3c2.Length];
  233. Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
  234. Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
  235. Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
  236. return result;
  237. }
  238. /**
  239. * c1||c3||c2
  240. * @param data
  241. * @param key
  242. * @return
  243. */
  244. public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
  245. {
  246. return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
  247. }
  248. /**
  249. * c1||c3||c2
  250. * @param data
  251. * @param key
  252. * @return
  253. */
  254. public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
  255. {
  256. return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
  257. }
  258. /**
  259. * c1||c2||c3
  260. * @param data
  261. * @param key
  262. * @return
  263. */
  264. public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
  265. {
  266. try
  267. {
  268. SM2Engine sm2Engine = new SM2Engine();
  269. sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
  270. return sm2Engine.ProcessBlock(data, 0, data.Length);
  271. }
  272. catch (Exception e)
  273. {
  274. ////log.Error("Sm2EncryptOld error: " + e.Message, e);
  275. return null;
  276. }
  277. }
  278. /**
  279. * c1||c2||c3
  280. * @param data
  281. * @param key
  282. * @return
  283. */
  284. public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
  285. {
  286. try
  287. {
  288. SM2Engine sm2Engine = new SM2Engine();
  289. sm2Engine.Init(false, key);
  290. return sm2Engine.ProcessBlock(data, 0, data.Length);
  291. }
  292. catch (Exception e)
  293. {
  294. ////log.Error("Sm2DecryptOld error: " + e.Message, e);
  295. return null;
  296. }
  297. }
  298. /**
  299. * @param bytes
  300. * @return
  301. */
  302. public static byte[] Sm3(byte[] bytes)
  303. {
  304. try
  305. {
  306. SM3Digest digest = new SM3Digest();
  307. digest.BlockUpdate(bytes, 0, bytes.Length);
  308. byte[] result = DigestUtilities.DoFinal(digest);
  309. return result;
  310. }
  311. catch (Exception e)
  312. {
  313. //log.Error("Sm3 error: " + e.Message, e);
  314. return null;
  315. }
  316. }
  317. private const int RS_LEN = 32;
  318. private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
  319. {
  320. // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
  321. // r and s are the result of mod n, so they should be less than n and have length<=32
  322. byte[] rs = rOrS.ToByteArray();
  323. if (rs.Length == RS_LEN) return rs;
  324. else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
  325. else if (rs.Length < RS_LEN)
  326. {
  327. byte[] result = new byte[RS_LEN];
  328. Arrays.Fill(result, 0);
  329. Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
  330. return result;
  331. }
  332. else
  333. {
  334. throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
  335. }
  336. }
  337. /**
  338. * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
  339. * @param rsDer rs in asn1 format
  340. * @return sign result in plain byte array
  341. */
  342. private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
  343. {
  344. Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
  345. byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
  346. byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
  347. byte[] result = new byte[RS_LEN * 2];
  348. Buffer.BlockCopy(r, 0, result, 0, r.Length);
  349. Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
  350. return result;
  351. }
  352. /**
  353. * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
  354. * @param sign in plain byte array
  355. * @return rs result in asn1 format
  356. */
  357. private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
  358. {
  359. if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
  360. BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
  361. BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
  362. Asn1EncodableVector v = new Asn1EncodableVector();
  363. v.Add(new DerInteger(r));
  364. v.Add(new DerInteger(s));
  365. try
  366. {
  367. return new DerSequence(v).GetEncoded("DER");
  368. }
  369. catch (IOException e)
  370. {
  371. //log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
  372. return null;
  373. }
  374. }
  375. public static AsymmetricCipherKeyPair GenerateKeyPair()
  376. {
  377. try
  378. {
  379. ECKeyPairGenerator kpGen = new ECKeyPairGenerator();
  380. kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
  381. return kpGen.GenerateKeyPair();
  382. }
  383. catch (Exception e)
  384. {
  385. //log.Error("generateKeyPair error: " + e.Message, e);
  386. return null;
  387. }
  388. }
  389. public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
  390. {
  391. return new ECPrivateKeyParameters(d, ecDomainParameters);
  392. }
  393. public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
  394. {
  395. return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
  396. }
  397. public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
  398. {
  399. FileStream fileStream = null;
  400. try
  401. {
  402. //file.DirectoryName + "\\" + file.Name
  403. fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
  404. X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
  405. return certificate.GetPublicKey();
  406. }
  407. catch (Exception e)
  408. {
  409. //log.Error(file.Name + "读取失败,异常:" + e);
  410. }
  411. finally
  412. {
  413. if (fileStream != null)
  414. fileStream.Close();
  415. }
  416. return null;
  417. }
  418. public class Sm2Cert
  419. {
  420. public AsymmetricKeyParameter privateKey;
  421. public AsymmetricKeyParameter publicKey;
  422. public string certId;
  423. }
  424. private static byte[] ToByteArray(int i)
  425. {
  426. byte[] byteArray = new byte[4];
  427. byteArray[0] = (byte)(i >> 24);
  428. byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
  429. byteArray[2] = (byte)((i & 0xFFFF) >> 8);
  430. byteArray[3] = (byte)(i & 0xFF);
  431. return byteArray;
  432. }
  433. /**
  434. * 字节数组拼接
  435. *
  436. * @param params
  437. * @return
  438. */
  439. private static byte[] Join(params byte[][] byteArrays)
  440. {
  441. List<byte> byteSource = new List<byte>();
  442. for (int i = 0; i < byteArrays.Length; i++)
  443. {
  444. byteSource.AddRange(byteArrays[i]);
  445. }
  446. byte[] data = byteSource.ToArray();
  447. return data;
  448. }
  449. /**
  450. * 密钥派生函数
  451. *
  452. * @param Z
  453. * @param klen
  454. * 生成klen字节数长度的密钥
  455. * @return
  456. */
  457. private static byte[] KDF(byte[] Z, int klen)
  458. {
  459. int ct = 1;
  460. int end = (int)Math.Ceiling(klen * 1.0 / 32);
  461. List<byte> byteSource = new List<byte>();
  462. try
  463. {
  464. for (int i = 1; i < end; i++)
  465. {
  466. byteSource.AddRange(Sm3(Join(Z, ToByteArray(ct))));
  467. ct++;
  468. }
  469. byte[] last = Sm3(Join(Z, ToByteArray(ct)));
  470. if (klen % 32 == 0)
  471. {
  472. byteSource.AddRange(last);
  473. }
  474. else
  475. byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
  476. return byteSource.ToArray();
  477. }
  478. catch (Exception e)
  479. {
  480. //log.Error("KDF error: " + e.Message, e);
  481. }
  482. return null;
  483. }
  484. public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, string algo)
  485. {
  486. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  487. if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
  488. try
  489. {
  490. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  491. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  492. if (iv == null) iv = ZeroIv(algo);
  493. c.Init(false, new ParametersWithIV(key, iv));
  494. return c.DoFinal(cipher);
  495. }
  496. catch (Exception e)
  497. {
  498. //log.Error("Sm4DecryptCBC error: " + e.Message, e);
  499. return null;
  500. }
  501. }
  502. public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, string algo)
  503. {
  504. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  505. if (plain.Length % 16 != 0) throw new ArgumentException("err data length");
  506. try
  507. {
  508. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  509. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  510. if (iv == null) iv = ZeroIv(algo);
  511. c.Init(true, new ParametersWithIV(key, iv));
  512. return c.DoFinal(plain);
  513. }
  514. catch (Exception e)
  515. {
  516. //log.Error("Sm4EncryptCBC error: " + e.Message, e);
  517. return null;
  518. }
  519. }
  520. public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
  521. {
  522. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  523. if (plain.Length % 16 != 0) throw new ArgumentException("err data length");
  524. try
  525. {
  526. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  527. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  528. c.Init(true, key);
  529. return c.DoFinal(plain);
  530. }
  531. catch (Exception e)
  532. {
  533. //log.Error("Sm4EncryptECB error: " + e.Message, e);
  534. return null;
  535. }
  536. }
  537. public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
  538. {
  539. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  540. if (cipher.Length % 16 != 0) throw new ArgumentException("err data length");
  541. try
  542. {
  543. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  544. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  545. c.Init(false, key);
  546. return c.DoFinal(cipher);
  547. }
  548. catch (Exception e)
  549. {
  550. //log.Error("Sm4DecryptECB error: " + e.Message, e);
  551. return null;
  552. }
  553. }
  554. public const string SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
  555. public const string SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
  556. public const string SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
  557. /**
  558. * cfca官网CSP沙箱导出的sm2文件
  559. * @param pem 二进制原文
  560. * @param pwd 密码
  561. * @return
  562. */
  563. public static Sm2Cert readSm2File(byte[] pem, string pwd)
  564. {
  565. Sm2Cert sm2Cert = new Sm2Cert();
  566. try
  567. {
  568. Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
  569. // ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
  570. Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
  571. Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert
  572. // ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
  573. // ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
  574. Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
  575. byte[] key = KDF(Encoding.UTF8.GetBytes(pwd), 32);
  576. byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
  577. priKeyAsn1.GetOctets(),
  578. Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
  579. sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
  580. // //log.Info(Hex.toHexString(priKeyD));
  581. // ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
  582. Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
  583. X509Certificate x509 = new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
  584. sm2Cert.publicKey = x509.GetPublicKey();
  585. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
  586. return sm2Cert;
  587. }
  588. catch (Exception e)
  589. {
  590. //log.Error("readSm2File error: " + e.Message, e);
  591. return null;
  592. }
  593. }
  594. /**
  595. *
  596. * @param cert
  597. * @return
  598. */
  599. public static Sm2Cert ReadSm2X509Cert(byte[] cert)
  600. {
  601. Sm2Cert sm2Cert = new Sm2Cert();
  602. try
  603. {
  604. X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
  605. sm2Cert.publicKey = x509.GetPublicKey();
  606. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
  607. return sm2Cert;
  608. }
  609. catch (Exception e)
  610. {
  611. //log.Error("ReadSm2X509Cert error: " + e.Message, e);
  612. return null;
  613. }
  614. }
  615. public static byte[] ZeroIv(string algo)
  616. {
  617. try
  618. {
  619. IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
  620. int blockSize = cipher.GetBlockSize();
  621. byte[] iv = new byte[blockSize];
  622. Arrays.Fill(iv, 0);
  623. return iv;
  624. }
  625. catch (Exception e)
  626. {
  627. //log.Error("ZeroIv error: " + e.Message, e);
  628. return null;
  629. }
  630. }
  631. public class Sm2Vo
  632. {
  633. public string sm2_x;
  634. public string sm2_y;
  635. }
  636. /**
  637. * BASE64格式公钥转换为裸公钥
  638. * @param sm2Key
  639. * @return
  640. */
  641. private static Sm2Vo parseBase64TRawKey(string sm2Key)
  642. {
  643. if (null == sm2Key)
  644. {
  645. return null;
  646. }
  647. string sm2_asn1 = Hex.ToHexString(Convert.FromBase64String(sm2Key));
  648. if (!sm2_asn1.StartsWith(SM2_KEY_TITLE))
  649. {
  650. return null;
  651. }
  652. Sm2Vo sm2Cert = new Sm2Vo();
  653. string sm2_xy = sm2_asn1.Substring(SM2_KEY_TITLE.Length, sm2_asn1.Length - SM2_KEY_TITLE.Length);
  654. sm2Cert.sm2_x = sm2_xy.Substring(0, sm2_xy.Length / 2);
  655. sm2Cert.sm2_y = sm2_xy.Substring(sm2_xy.Length / 2, sm2_xy.Length - sm2_xy.Length / 2);
  656. return sm2Cert;
  657. }
  658. /**
  659. * 加签
  660. */
  661. public static string generateSmSign(string str)
  662. {
  663. AsymmetricKeyParameter SMprivateKey = GetPrivatekeyFromD(new BigInteger(SM_PRIVATE_KEY, 16));
  664. //1.国密签名
  665. byte[] msg = Encoding.UTF8.GetBytes(str);
  666. //签名 USER_ID 应使用国密局推荐 ID,即“1234567812345678”
  667. byte[] userId = Encoding.UTF8.GetBytes(SM_USER_ID);
  668. byte[] sig = SignSm3WithSm2(msg, userId, SMprivateKey);
  669. //国密加签结果
  670. string c = Convert.ToBase64String(signRawToAsn1(sig));
  671. return c;
  672. }
  673. /**
  674. * 验签
  675. */
  676. public static bool verifySmSign(string rawMsg, string signedStr)
  677. {
  678. byte[] sig2 = Convert.FromBase64String(signedStr);
  679. Sm2Vo sm2Vo = parseBase64TRawKey(SM_PUBLIC_KEY);
  680. string privateKeyRawX = sm2Vo.sm2_x;
  681. string privateKeyRawY = sm2Vo.sm2_y;
  682. AsymmetricKeyParameter SMPbkey = GetPublickeyFromXY(new BigInteger(privateKeyRawX, 16), new BigInteger(privateKeyRawY, 16));
  683. byte[] sig3 = signAsn12Raw(sig2);
  684. byte[] msg = Encoding.UTF8.GetBytes(rawMsg);
  685. //签名 USER_ID 应使用国密局推荐 ID,即“1234567812345678”
  686. byte[] userId = Encoding.UTF8.GetBytes(SM_USER_ID);
  687. bool flag = VerifySm3WithSm2(msg, userId, sig3, SMPbkey);
  688. return flag;
  689. }
  690. }
  691. }