C#.NET 国密SM2 签名验签 与JAVA互通 ver:20230807

.NET 环境:.NET6 控制台程序(.net core)。

JAVA 环境:JAVA8(JDK8,JAVA 1.8),带maven 的JAVA控制台程序。

1.最好要到对方源码(DEMO+JAR包也可以),可以用IDEA反编译(Ctrl+鼠标左键),看它过程逻辑和结果格式。

2.常说的SM2签名,指的就是“SM3withSM2”。类似于:SHA256withRSA,SHA1withRSA。

3.签名结果:有2种格式:r||s 和 asn1 ,双方得约定好。
SignSm3WithSm2 是RS,SignSm3WithSm2Asn1Rs 是 asn1,一种不行就换另一种调试。

4.签名结果传输,可以转BASE64字符串或16进制字符串,双方得约定好。

5.如果未指明 userId: 那默认值就是:1234567812345678。
string userId = "1234567812345678";

6.有的文档说是进行 sm3 hash 后进行 sm2 签名,我们以为是:
var rstA=sm3hash(dataString);
var rstB= SignSm3WithSm2(rstA);
但实际只有一步:
var rstB= SignSm3WithSm2(dataString);
文档描述和代码逻辑有出入的地方很多,所以得找对方要代码DEMO,Show me the code !

7.有的签名代码和BC库是不兼容的,得少量手动实现:https://www.cnblogs.com/runliuv/p/16486898.html。

注意:JAVA的 HUTOOL - sm2.sign 结果格式是 RS 的,我们得用 VerifySm3WithSm2Asn1Rs。

生成一组国密公私钥:

私钥:FAB8BBE670FAE338C9E9382B9FB6485225C11A3ECB84C938F10F20A93B6215F0

公钥:049EF573019D9A03B16B0BE44FC8A5B4E8E098F56034C97B312282DD0B4810AFC3CC759673ED0FC9B9DC7E6FA38F0E2B121E02654BF37EA6B63FAF2A0D6013EADF

.NET 代码:

GmUtil 工具类,需要nuget下载 Portable.BouncyCastle 1.9.0 版本:

  1. using Org.BouncyCastle.Asn1;
  2. using Org.BouncyCastle.Asn1.GM;
  3. using Org.BouncyCastle.Asn1.X9;
  4. using Org.BouncyCastle.Crypto;
  5. using Org.BouncyCastle.Crypto.Digests;
  6. using Org.BouncyCastle.Crypto.Engines;
  7. using Org.BouncyCastle.Crypto.Generators;
  8. using Org.BouncyCastle.Crypto.Parameters;
  9. using Org.BouncyCastle.Math;
  10. using Org.BouncyCastle.Security;
  11. using Org.BouncyCastle.Utilities;
  12. using Org.BouncyCastle.Utilities.Encoders;
  13. using Org.BouncyCastle.X509;
  14. using System;
  15. using System.Collections.Generic;
  16. using System.IO;
  17.  
  18. namespace CommonUtils
  19. {
  20. /**
  21. * need lib:
  22. * BouncyCastle.Crypto.dll(http://www.bouncycastle.org/csharp/index.html)
  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. * 按要求国密算法仅允许使用加密机,本demo国密算法仅供学习使用,请不要用于生产用途。
  29. */
  30. public class GmUtil
  31. {
  32.  
  33. //private static readonly ILog log = LogManager.GetLogger(typeof(GmUtil));
  34.  
  35. private static X9ECParameters x9ECParameters = GMNamedCurves.GetByName("sm2p256v1");
  36. private static ECDomainParameters ecDomainParameters = new ECDomainParameters(x9ECParameters.Curve, x9ECParameters.G, x9ECParameters.N);
  37.  
  38. /**
  39. *
  40. * @param msg
  41. * @param userId
  42. * @param privateKey
  43. * @return r||s,直接拼接byte数组的rs
  44. */
  45. public static byte[] SignSm3WithSm2(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  46. {
  47. return RsAsn1ToPlainByteArray(SignSm3WithSm2Asn1Rs(msg, userId, privateKey));
  48. }
  49.  
  50. /**
  51. * @param msg
  52. * @param userId
  53. * @param privateKey
  54. * @return rs in <b>asn1 format</b>
  55. */
  56. public static byte[] SignSm3WithSm2Asn1Rs(byte[] msg, byte[] userId, AsymmetricKeyParameter privateKey)
  57. {
  58. try
  59. {
  60. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  61. signer.Init(true, new ParametersWithID(privateKey, userId));
  62. signer.BlockUpdate(msg, 0, msg.Length);
  63. byte[] sig = signer.GenerateSignature();
  64. return sig;
  65. }
  66. catch (Exception e)
  67. {
  68. //log.Error("SignSm3WithSm2Asn1Rs error: " + e.Message, e);
  69. return null;
  70. }
  71. }
  72.  
  73. /**
  74. *
  75. * @param msg
  76. * @param userId
  77. * @param rs r||s,直接拼接byte数组的rs
  78. * @param publicKey
  79. * @return
  80. */
  81. public static bool VerifySm3WithSm2(byte[] msg, byte[] userId, byte[] rs, AsymmetricKeyParameter publicKey)
  82. {
  83. if (rs == null || msg == null || userId == null) return false;
  84. if (rs.Length != RS_LEN * 2) return false;
  85. return VerifySm3WithSm2Asn1Rs(msg, userId, RsPlainByteArrayToAsn1(rs), publicKey);
  86. }
  87.  
  88. /**
  89. *
  90. * @param msg
  91. * @param userId
  92. * @param rs in <b>asn1 format</b>
  93. * @param publicKey
  94. * @return
  95. */
  96.  
  97. public static bool VerifySm3WithSm2Asn1Rs(byte[] msg, byte[] userId, byte[] sign, AsymmetricKeyParameter publicKey)
  98. {
  99. try
  100. {
  101. ISigner signer = SignerUtilities.GetSigner("SM3withSM2");
  102. signer.Init(false, new ParametersWithID(publicKey, userId));
  103. signer.BlockUpdate(msg, 0, msg.Length);
  104. return signer.VerifySignature(sign);
  105. }
  106. catch (Exception e)
  107. {
  108. //log.Error("VerifySm3WithSm2Asn1Rs error: " + e.Message, e);
  109. return false;
  110. }
  111. }
  112.  
  113. /**
  114. * bc加解密使用旧标c1||c2||c3,此方法在加密后调用,将结果转化为c1||c3||c2
  115. * @param c1c2c3
  116. * @return
  117. */
  118. private static byte[] ChangeC1C2C3ToC1C3C2(byte[] c1c2c3)
  119. {
  120. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  121. const int c3Len = 32; //new SM3Digest().getDigestSize();
  122. byte[] result = new byte[c1c2c3.Length];
  123. Buffer.BlockCopy(c1c2c3, 0, result, 0, c1Len); //c1
  124. Buffer.BlockCopy(c1c2c3, c1c2c3.Length - c3Len, result, c1Len, c3Len); //c3
  125. Buffer.BlockCopy(c1c2c3, c1Len, result, c1Len + c3Len, c1c2c3.Length - c1Len - c3Len); //c2
  126. return result;
  127. }
  128.  
  129. /**
  130. * bc加解密使用旧标c1||c3||c2,此方法在解密前调用,将密文转化为c1||c2||c3再去解密
  131. * @param c1c3c2
  132. * @return
  133. */
  134. private static byte[] ChangeC1C3C2ToC1C2C3(byte[] c1c3c2)
  135. {
  136. int c1Len = (x9ECParameters.Curve.FieldSize + 7) / 8 * 2 + 1; //sm2p256v1的这个固定65。可看GMNamedCurves、ECCurve代码。
  137. const int c3Len = 32; //new SM3Digest().GetDigestSize();
  138. byte[] result = new byte[c1c3c2.Length];
  139. Buffer.BlockCopy(c1c3c2, 0, result, 0, c1Len); //c1: 0->65
  140. Buffer.BlockCopy(c1c3c2, c1Len + c3Len, result, c1Len, c1c3c2.Length - c1Len - c3Len); //c2
  141. Buffer.BlockCopy(c1c3c2, c1Len, result, c1c3c2.Length - c3Len, c3Len); //c3
  142. return result;
  143. }
  144.  
  145. /**
  146. * c1||c3||c2
  147. * @param data
  148. * @param key
  149. * @return
  150. */
  151. public static byte[] Sm2Decrypt(byte[] data, AsymmetricKeyParameter key)
  152. {
  153. return Sm2DecryptOld(ChangeC1C3C2ToC1C2C3(data), key);
  154. }
  155.  
  156. /**
  157. * c1||c3||c2
  158. * @param data
  159. * @param key
  160. * @return
  161. */
  162.  
  163. public static byte[] Sm2Encrypt(byte[] data, AsymmetricKeyParameter key)
  164. {
  165. return ChangeC1C2C3ToC1C3C2(Sm2EncryptOld(data, key));
  166. }
  167.  
  168. /**
  169. * c1||c2||c3
  170. * @param data
  171. * @param key
  172. * @return
  173. */
  174. public static byte[] Sm2EncryptOld(byte[] data, AsymmetricKeyParameter pubkey)
  175. {
  176. try
  177. {
  178. SM2Engine sm2Engine = new SM2Engine();
  179. sm2Engine.Init(true, new ParametersWithRandom(pubkey, new SecureRandom()));
  180. return sm2Engine.ProcessBlock(data, 0, data.Length);
  181. }
  182. catch (Exception e)
  183. {
  184. //log.Error("Sm2EncryptOld error: " + e.Message, e);
  185. return null;
  186. }
  187. }
  188.  
  189. /**
  190. * c1||c2||c3
  191. * @param data
  192. * @param key
  193. * @return
  194. */
  195. public static byte[] Sm2DecryptOld(byte[] data, AsymmetricKeyParameter key)
  196. {
  197. try
  198. {
  199. SM2Engine sm2Engine = new SM2Engine();
  200. sm2Engine.Init(false, key);
  201. return sm2Engine.ProcessBlock(data, 0, data.Length);
  202. }
  203. catch (Exception e)
  204. {
  205. //log.Error("Sm2DecryptOld error: " + e.Message, e);
  206. return null;
  207. }
  208. }
  209.  
  210. /**
  211. * @param bytes
  212. * @return
  213. */
  214. public static byte[] Sm3(byte[] bytes)
  215. {
  216. try
  217. {
  218. SM3Digest digest = new SM3Digest();
  219. digest.BlockUpdate(bytes, 0, bytes.Length);
  220. byte[] result = DigestUtilities.DoFinal(digest);
  221. return result;
  222. }
  223. catch (Exception e)
  224. {
  225. //log.Error("Sm3 error: " + e.Message, e);
  226. return null;
  227. }
  228. }
  229.  
  230. private const int RS_LEN = 32;
  231.  
  232. private static byte[] BigIntToFixexLengthBytes(BigInteger rOrS)
  233. {
  234. // for sm2p256v1, n is 00fffffffeffffffffffffffffffffffff7203df6b21c6052b53bbf40939d54123,
  235. // r and s are the result of mod n, so they should be less than n and have length<=32
  236. byte[] rs = rOrS.ToByteArray();
  237. if (rs.Length == RS_LEN) return rs;
  238. else if (rs.Length == RS_LEN + 1 && rs[0] == 0) return Arrays.CopyOfRange(rs, 1, RS_LEN + 1);
  239. else if (rs.Length < RS_LEN)
  240. {
  241. byte[] result = new byte[RS_LEN];
  242. Arrays.Fill(result, (byte)0);
  243. Buffer.BlockCopy(rs, 0, result, RS_LEN - rs.Length, rs.Length);
  244. return result;
  245. }
  246. else
  247. {
  248. throw new ArgumentException("err rs: " + Hex.ToHexString(rs));
  249. }
  250. }
  251.  
  252. /**
  253. * BC的SM3withSM2签名得到的结果的rs是asn1格式的,这个方法转化成直接拼接r||s
  254. * @param rsDer rs in asn1 format
  255. * @return sign result in plain byte array
  256. */
  257. private static byte[] RsAsn1ToPlainByteArray(byte[] rsDer)
  258. {
  259. Asn1Sequence seq = Asn1Sequence.GetInstance(rsDer);
  260. byte[] r = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[0]).Value);
  261. byte[] s = BigIntToFixexLengthBytes(DerInteger.GetInstance(seq[1]).Value);
  262. byte[] result = new byte[RS_LEN * 2];
  263. Buffer.BlockCopy(r, 0, result, 0, r.Length);
  264. Buffer.BlockCopy(s, 0, result, RS_LEN, s.Length);
  265. return result;
  266. }
  267.  
  268. /**
  269. * BC的SM3withSM2验签需要的rs是asn1格式的,这个方法将直接拼接r||s的字节数组转化成asn1格式
  270. * @param sign in plain byte array
  271. * @return rs result in asn1 format
  272. */
  273. private static byte[] RsPlainByteArrayToAsn1(byte[] sign)
  274. {
  275. if (sign.Length != RS_LEN * 2) throw new ArgumentException("err rs. ");
  276. BigInteger r = new BigInteger(1, Arrays.CopyOfRange(sign, 0, RS_LEN));
  277. BigInteger s = new BigInteger(1, Arrays.CopyOfRange(sign, RS_LEN, RS_LEN * 2));
  278. Asn1EncodableVector v = new Asn1EncodableVector();
  279. v.Add(new DerInteger(r));
  280. v.Add(new DerInteger(s));
  281. try
  282. {
  283. return new DerSequence(v).GetEncoded("DER");
  284. }
  285. catch (IOException e)
  286. {
  287. //log.Error("RsPlainByteArrayToAsn1 error: " + e.Message, e);
  288. return null;
  289. }
  290. }
  291.  
  292. public static AsymmetricCipherKeyPair GenerateKeyPair()
  293. {
  294. try
  295. {
  296. ECKeyPairGenerator kpGen = new ECKeyPairGenerator();
  297. kpGen.Init(new ECKeyGenerationParameters(ecDomainParameters, new SecureRandom()));
  298. return kpGen.GenerateKeyPair();
  299. }
  300. catch (Exception e)
  301. {
  302. //log.Error("generateKeyPair error: " + e.Message, e);
  303. return null;
  304. }
  305. }
  306.  
  307. public static ECPrivateKeyParameters GetPrivatekeyFromD(BigInteger d)
  308. {
  309. return new ECPrivateKeyParameters(d, ecDomainParameters);
  310. }
  311.  
  312. public static ECPublicKeyParameters GetPublickeyFromXY(BigInteger x, BigInteger y)
  313. {
  314. return new ECPublicKeyParameters(x9ECParameters.Curve.CreatePoint(x, y), ecDomainParameters);
  315. }
  316.  
  317. public static AsymmetricKeyParameter GetPublickeyFromX509File(FileInfo file)
  318. {
  319.  
  320. FileStream fileStream = null;
  321. try
  322. {
  323. //file.DirectoryName + "\\" + file.Name
  324. fileStream = new FileStream(file.FullName, FileMode.Open, FileAccess.Read);
  325. X509Certificate certificate = new X509CertificateParser().ReadCertificate(fileStream);
  326. return certificate.GetPublicKey();
  327. }
  328. catch (Exception e)
  329. {
  330. //log.Error(file.Name + "读取失败,异常:" + e);
  331. }
  332. finally
  333. {
  334. if (fileStream != null)
  335. fileStream.Close();
  336. }
  337. return null;
  338. }
  339.  
  340. public class Sm2Cert
  341. {
  342. public AsymmetricKeyParameter privateKey;
  343. public AsymmetricKeyParameter publicKey;
  344. public String certId;
  345. }
  346.  
  347. private static byte[] ToByteArray(int i)
  348. {
  349. byte[] byteArray = new byte[4];
  350. byteArray[0] = (byte)(i >> 24);
  351. byteArray[1] = (byte)((i & 0xFFFFFF) >> 16);
  352. byteArray[2] = (byte)((i & 0xFFFF) >> 8);
  353. byteArray[3] = (byte)(i & 0xFF);
  354. return byteArray;
  355. }
  356.  
  357. /**
  358. * 字节数组拼接
  359. *
  360. * @param params
  361. * @return
  362. */
  363. private static byte[] Join(params byte[][] byteArrays)
  364. {
  365. List<byte> byteSource = new List<byte>();
  366. for (int i = 0; i < byteArrays.Length; i++)
  367. {
  368. byteSource.AddRange(byteArrays[i]);
  369. }
  370. byte[] data = byteSource.ToArray();
  371. return data;
  372. }
  373.  
  374. /**
  375. * 密钥派生函数
  376. *
  377. * @param Z
  378. * @param klen
  379. * 生成klen字节数长度的密钥
  380. * @return
  381. */
  382. private static byte[] KDF(byte[] Z, int klen)
  383. {
  384. int ct = 1;
  385. int end = (int)Math.Ceiling(klen * 1.0 / 32);
  386. List<byte> byteSource = new List<byte>();
  387. try
  388. {
  389. for (int i = 1; i < end; i++)
  390. {
  391. byteSource.AddRange(GmUtil.Sm3(Join(Z, ToByteArray(ct))));
  392. ct++;
  393. }
  394. byte[] last = GmUtil.Sm3(Join(Z, ToByteArray(ct)));
  395. if (klen % 32 == 0)
  396. {
  397. byteSource.AddRange(last);
  398. }
  399. else
  400. byteSource.AddRange(Arrays.CopyOfRange(last, 0, klen % 32));
  401. return byteSource.ToArray();
  402. }
  403. catch (Exception e)
  404. {
  405. //log.Error("KDF error: " + e.Message, e);
  406. }
  407. return null;
  408. }
  409.  
  410. public static byte[] Sm4DecryptCBC(byte[] keyBytes, byte[] cipher, byte[] iv, String algo)
  411. {
  412. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  413. if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  414.  
  415. try
  416. {
  417. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  418. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  419. if (iv == null) iv = ZeroIv(algo);
  420. c.Init(false, new ParametersWithIV(key, iv));
  421. return c.DoFinal(cipher);
  422. }
  423. catch (Exception e)
  424. {
  425. //log.Error("Sm4DecryptCBC error: " + e.Message, e);
  426. return null;
  427. }
  428. }
  429.  
  430. public static byte[] Sm4EncryptCBC(byte[] keyBytes, byte[] plain, byte[] iv, String algo)
  431. {
  432. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  433. if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  434.  
  435. try
  436. {
  437. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  438. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  439. if (iv == null) iv = ZeroIv(algo);
  440. c.Init(true, new ParametersWithIV(key, iv));
  441. return c.DoFinal(plain);
  442. }
  443. catch (Exception e)
  444. {
  445. //log.Error("Sm4EncryptCBC error: " + e.Message, e);
  446. return null;
  447. }
  448. }
  449.  
  450. public static byte[] Sm4EncryptECB(byte[] keyBytes, byte[] plain, string algo)
  451. {
  452. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  453. //NoPadding 的情况下需要校验数据长度是16的倍数.
  454. if (plain.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  455.  
  456. try
  457. {
  458. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  459. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  460. c.Init(true, key);
  461. return c.DoFinal(plain);
  462. }
  463. catch (Exception e)
  464. {
  465. //log.Error("Sm4EncryptECB error: " + e.Message, e);
  466. return null;
  467. }
  468. }
  469.  
  470. public static byte[] Sm4DecryptECB(byte[] keyBytes, byte[] cipher, string algo)
  471. {
  472. if (keyBytes.Length != 16) throw new ArgumentException("err key length");
  473. if (cipher.Length % 16 != 0 && algo.Contains("NoPadding")) throw new ArgumentException("err data length");
  474.  
  475. try
  476. {
  477. KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
  478. IBufferedCipher c = CipherUtilities.GetCipher(algo);
  479. c.Init(false, key);
  480. return c.DoFinal(cipher);
  481. }
  482. catch (Exception e)
  483. {
  484. //log.Error("Sm4DecryptECB error: " + e.Message, e);
  485. return null;
  486. }
  487. }
  488.  
  489. public const String SM4_ECB_NOPADDING = "SM4/ECB/NoPadding";
  490. public const String SM4_CBC_NOPADDING = "SM4/CBC/NoPadding";
  491. public const String SM4_CBC_PKCS7PADDING = "SM4/CBC/PKCS7Padding";
  492.  
  493. /**
  494. * cfca官网CSP沙箱导出的sm2文件
  495. * @param pem 二进制原文
  496. * @param pwd 密码
  497. * @return
  498. */
  499. public static Sm2Cert readSm2File(byte[] pem, String pwd)
  500. {
  501.  
  502. Sm2Cert sm2Cert = new Sm2Cert();
  503. try
  504. {
  505. Asn1Sequence asn1Sequence = (Asn1Sequence)Asn1Object.FromByteArray(pem);
  506. // ASN1Integer asn1Integer = (ASN1Integer) asn1Sequence.getObjectAt(0); //version=1
  507. Asn1Sequence priSeq = (Asn1Sequence)asn1Sequence[1];//private key
  508. Asn1Sequence pubSeq = (Asn1Sequence)asn1Sequence[2];//public key and x509 cert
  509.  
  510. // ASN1ObjectIdentifier sm2DataOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(0);
  511. // ASN1ObjectIdentifier sm4AlgOid = (ASN1ObjectIdentifier) priSeq.getObjectAt(1);
  512. Asn1OctetString priKeyAsn1 = (Asn1OctetString)priSeq[2];
  513. byte[] key = KDF(System.Text.Encoding.UTF8.GetBytes(pwd), 32);
  514. byte[] priKeyD = Sm4DecryptCBC(Arrays.CopyOfRange(key, 16, 32),
  515. priKeyAsn1.GetOctets(),
  516. Arrays.CopyOfRange(key, 0, 16), SM4_CBC_PKCS7PADDING);
  517. sm2Cert.privateKey = GetPrivatekeyFromD(new BigInteger(1, priKeyD));
  518. // log.Info(Hex.toHexString(priKeyD));
  519.  
  520. // ASN1ObjectIdentifier sm2DataOidPub = (ASN1ObjectIdentifier) pubSeq.getObjectAt(0);
  521. Asn1OctetString pubKeyX509 = (Asn1OctetString)pubSeq[1];
  522. X509Certificate x509 = (X509Certificate)new X509CertificateParser().ReadCertificate(pubKeyX509.GetOctets());
  523. sm2Cert.publicKey = x509.GetPublicKey();
  524. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
  525. return sm2Cert;
  526. }
  527. catch (Exception e)
  528. {
  529. //log.Error("readSm2File error: " + e.Message, e);
  530. return null;
  531. }
  532. }
  533.  
  534. /**
  535. *
  536. * @param cert
  537. * @return
  538. */
  539. public static Sm2Cert ReadSm2X509Cert(byte[] cert)
  540. {
  541. Sm2Cert sm2Cert = new Sm2Cert();
  542. try
  543. {
  544.  
  545. X509Certificate x509 = new X509CertificateParser().ReadCertificate(cert);
  546. sm2Cert.publicKey = x509.GetPublicKey();
  547. sm2Cert.certId = x509.SerialNumber.ToString(10); //这里转10进账,有啥其他进制要求的自己改改
  548. return sm2Cert;
  549. }
  550. catch (Exception e)
  551. {
  552. //log.Error("ReadSm2X509Cert error: " + e.Message, e);
  553. return null;
  554. }
  555. }
  556.  
  557. public static byte[] ZeroIv(String algo)
  558. {
  559.  
  560. try
  561. {
  562. IBufferedCipher cipher = CipherUtilities.GetCipher(algo);
  563. int blockSize = cipher.GetBlockSize();
  564. byte[] iv = new byte[blockSize];
  565. Arrays.Fill(iv, (byte)0);
  566. return iv;
  567. }
  568. catch (Exception e)
  569. {
  570. //log.Error("ZeroIv error: " + e.Message, e);
  571. return null;
  572. }
  573. }
  574.  
  575. public static void Main2(string[] s)
  576. {
  577.  
  578. // 随便看看
  579. //log.Info("GMNamedCurves: ");
  580. foreach (string e in GMNamedCurves.Names)
  581. {
  582. //log.Info(e);
  583. }
  584. //log.Info("sm2p256v1 n:" + x9ECParameters.N);
  585. //log.Info("sm2p256v1 nHex:" + Hex.ToHexString(x9ECParameters.N.ToByteArray()));
  586.  
  587. // 生成公私钥对 ---------------------
  588. AsymmetricCipherKeyPair kp = GmUtil.GenerateKeyPair();
  589. //log.Info("private key d: " + ((ECPrivateKeyParameters)kp.Private).D);
  590. //log.Info("public key q:" + ((ECPublicKeyParameters)kp.Public).Q); //{x, y, zs...}
  591.  
  592. //签名验签
  593. byte[] msg = System.Text.Encoding.UTF8.GetBytes("message digest");
  594. byte[] userId = System.Text.Encoding.UTF8.GetBytes("userId");
  595. byte[] sig = SignSm3WithSm2(msg, userId, kp.Private);
  596. //log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
  597. //log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, kp.Public));
  598.  
  599. // 由d生成私钥 ---------------------
  600. BigInteger d = new BigInteger("097b5230ef27c7df0fa768289d13ad4e8a96266f0fcb8de40d5942af4293a54a", 16);
  601. ECPrivateKeyParameters bcecPrivateKey = GetPrivatekeyFromD(d);
  602. //log.Info("testGetFromD: " + bcecPrivateKey.D.ToString(16));
  603.  
  604. //公钥X坐标PublicKeyXHex: 59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4
  605. //公钥Y坐标PublicKeyYHex: 9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8
  606. AsymmetricKeyParameter publicKey = GetPublickeyFromX509File(new FileInfo("d:/certs/69629141652.cer"));
  607. //log.Info(publicKey);
  608. AsymmetricKeyParameter publicKey1 = GetPublickeyFromXY(new BigInteger("59cf9940ea0809a97b1cbffbb3e9d96d0fe842c1335418280bfc51dd4e08a5d4", 16), new BigInteger("9a7f77c578644050e09a9adc4245d1e6eba97554bc8ffd4fe15a78f37f891ff8", 16));
  609. //log.Info("testReadFromX509File: " + ((ECPublicKeyParameters)publicKey).Q);
  610. //log.Info("testGetFromXY: " + ((ECPublicKeyParameters)publicKey1).Q);
  611. //log.Info("testPubKey: " + publicKey.Equals(publicKey1));
  612. //log.Info("testPubKey: " + ((ECPublicKeyParameters)publicKey).Q.Equals(((ECPublicKeyParameters)publicKey1).Q));
  613.  
  614. // sm2 encrypt and decrypt test ---------------------
  615. AsymmetricCipherKeyPair kp2 = GenerateKeyPair();
  616. AsymmetricKeyParameter publicKey2 = kp2.Public;
  617. AsymmetricKeyParameter privateKey2 = kp2.Private;
  618. byte[] bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), publicKey2);
  619. //log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
  620. bs = Sm2Decrypt(bs, privateKey2);
  621. //log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs));
  622.  
  623. // sm4 encrypt and decrypt test ---------------------
  624. //0123456789abcdeffedcba9876543210 + 0123456789abcdeffedcba9876543210 -> 681edf34d206965e86b3e94f536e4246
  625. byte[] plain = Hex.Decode("0123456789abcdeffedcba98765432100123456789abcdeffedcba98765432100123456789abcdeffedcba9876543210");
  626. byte[] key = Hex.Decode("0123456789abcdeffedcba9876543210");
  627. byte[] cipher = Hex.Decode("595298c7c6fd271f0402f804c33d3f66");
  628. bs = Sm4EncryptECB(key, plain, GmUtil.SM4_ECB_NOPADDING);
  629. //log.Info("testSm4EncEcb: " + Hex.ToHexString(bs)); ;
  630. bs = Sm4DecryptECB(key, bs, GmUtil.SM4_ECB_NOPADDING);
  631. //log.Info("testSm4DecEcb: " + Hex.ToHexString(bs));
  632.  
  633. //读.sm2文件
  634. String sm2 = "MIIDHQIBATBHBgoqgRzPVQYBBAIBBgcqgRzPVQFoBDDW5/I9kZhObxXE9Vh1CzHdZhIhxn+3byBU\nUrzmGRKbDRMgI3hJKdvpqWkM5G4LNcIwggLNBgoqgRzPVQYBBAIBBIICvTCCArkwggJdoAMCAQIC\nBRA2QSlgMAwGCCqBHM9VAYN1BQAwXDELMAkGA1UEBhMCQ04xMDAuBgNVBAoMJ0NoaW5hIEZpbmFu\nY2lhbCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTEbMBkGA1UEAwwSQ0ZDQSBURVNUIFNNMiBPQ0Ex\nMB4XDTE4MTEyNjEwMTQxNVoXDTIwMTEyNjEwMTQxNVowcjELMAkGA1UEBhMCY24xEjAQBgNVBAoM\nCUNGQ0EgT0NBMTEOMAwGA1UECwwFQ1VQUkExFDASBgNVBAsMC0VudGVycHJpc2VzMSkwJwYDVQQD\nDCAwNDFAWnRlc3RAMDAwMTAwMDA6U0lHTkAwMDAwMDAwMTBZMBMGByqGSM49AgEGCCqBHM9VAYIt\nA0IABDRNKhvnjaMUShsM4MJ330WhyOwpZEHoAGfqxFGX+rcL9x069dyrmiF3+2ezwSNh1/6YqfFZ\nX9koM9zE5RG4USmjgfMwgfAwHwYDVR0jBBgwFoAUa/4Y2o9COqa4bbMuiIM6NKLBMOEwSAYDVR0g\nBEEwPzA9BghggRyG7yoBATAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2EuY29tLmNuL3Vz\nL3VzLTE0Lmh0bTA4BgNVHR8EMTAvMC2gK6AphidodHRwOi8vdWNybC5jZmNhLmNvbS5jbi9TTTIv\nY3JsNDI4NS5jcmwwCwYDVR0PBAQDAgPoMB0GA1UdDgQWBBREhx9VlDdMIdIbhAxKnGhPx8FcHDAd\nBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDAYIKoEcz1UBg3UFAANIADBFAiEAgWvQi3h6\niW4jgF4huuXfhWInJmTTYr2EIAdG8V4M8fYCIBixygdmfPL9szcK2pzCYmIb6CBzo5SMv50Odycc\nVfY6";
  635. bs = Convert.FromBase64String(sm2);
  636. String pwd = "cfca1234";
  637. GmUtil.Sm2Cert sm2Cert = GmUtil.readSm2File(bs, pwd);
  638. //log.Info("testReadSm2File, pubkey: " + ((ECPublicKeyParameters)sm2Cert.publicKey).Q.ToString());
  639. //log.Info("testReadSm2File, prikey: " + Hex.ToHexString(((ECPrivateKeyParameters)sm2Cert.privateKey).D.ToByteArray()));
  640. //log.Info("testReadSm2File, certId: " + sm2Cert.certId);
  641.  
  642. bs = Sm2Encrypt(System.Text.Encoding.UTF8.GetBytes("s"), ((ECPublicKeyParameters)sm2Cert.publicKey));
  643. //log.Info("testSm2Enc dec: " + Hex.ToHexString(bs));
  644. bs = Sm2Decrypt(bs, ((ECPrivateKeyParameters)sm2Cert.privateKey));
  645. //log.Info("testSm2Enc dec: " + System.Text.Encoding.UTF8.GetString(bs));
  646.  
  647. msg = System.Text.Encoding.UTF8.GetBytes("message digest");
  648. userId = System.Text.Encoding.UTF8.GetBytes("userId");
  649. sig = SignSm3WithSm2(msg, userId, ((ECPrivateKeyParameters)sm2Cert.privateKey));
  650. //log.Info("testSignSm3WithSm2: " + Hex.ToHexString(sig));
  651. //log.Info("testVerifySm3WithSm2: " + VerifySm3WithSm2(msg, userId, sig, ((ECPublicKeyParameters)sm2Cert.publicKey)));
  652. }
  653.  
  654. }
  655. }

.NET使用:

  1. using CommonUtils;
  2. using Org.BouncyCastle.Crypto;
  3. using Org.BouncyCastle.Math;
  4. using Org.BouncyCastle.Utilities.Encoders;
  5. using System.Text;
  6.  
  7. void TestSM2Sign()
  8. {
  9. string userId = "1234567812345678";
  10. byte[] byUserId = Encoding.UTF8.GetBytes(userId);
  11. String privateKeyHex = "FAB8BBE670FAE338C9E9382B9FB6485225C11A3ECB84C938F10F20A93B6215F0";
  12. string pubKeyHex = "049EF573019D9A03B16B0BE44FC8A5B4E8E098F56034C97B312282DD0B4810AFC3CC759673ED0FC9B9DC7E6FA38F0E2B121E02654BF37EA6B63FAF2A0D6013EADF";
  13. //如果是130位公钥,.NET 使用的话,把开头的04截取掉。
  14. if (pubKeyHex.Length == 130)
  15. {
  16. pubKeyHex = pubKeyHex.Substring(2, 128);
  17. }
  18. //公钥X,前64位
  19. String x = pubKeyHex.Substring(0, 64);
  20. //公钥Y,后64位
  21. String y = pubKeyHex.Substring(64);
  22. //获取公钥对象
  23. AsymmetricKeyParameter publicKey1 = GmUtil.GetPublickeyFromXY(new BigInteger(x, 16), new BigInteger(y, 16));
  24. BigInteger d = new BigInteger(privateKeyHex, 16);
  25. //获取私钥对象,用ECPrivateKeyParameters 或 AsymmetricKeyParameter 都可以
  26. //ECPrivateKeyParameters bcecPrivateKey = CommonUtils.GmUtil.GetPrivatekeyFromD(d);
  27. AsymmetricKeyParameter bcecPrivateKey = CommonUtils.GmUtil.GetPrivatekeyFromD(d);
  28.  
  29. String content = "1234泰酷拉NET";
  30. Console.WriteLine("待处理字符串:" + content);
  31. //SignSm3WithSm2 是RS,SignSm3WithSm2Asn1Rs 是 asn1
  32. byte[] digestByte = GmUtil.SignSm3WithSm2(Encoding.UTF8.GetBytes(content), byUserId, bcecPrivateKey);
  33. string strSM2 = Convert.ToBase64String(digestByte);
  34. Console.WriteLine("SM2加签后:" + strSM2);
  35.  
  36. //.NET 验签
  37. byte[] byToProc = Convert.FromBase64String(strSM2);
  38. //顺序:报文,userId,签名值,公钥。
  39. bool verifySign = GmUtil.VerifySm3WithSm2(Encoding.UTF8.GetBytes(content), byUserId, byToProc, publicKey1);
  40.  
  41. Console.WriteLine("SM2 验签:" + verifySign.ToString());
  42.  
  43. //JAVA 签名 .NET验签
  44. string javaContent = "1234泰酷拉JJ"; //注意:报文要和JAVA一致
  45. Console.WriteLine("javaContent:" + javaContent);
  46. string javaSM2 = "MEUCIF5PXxIlF0NmQaUtfIGLbZm4JuYT4bkYyoFMA/eIqVaUAiEAkRT3GkrtY2YtUSF9Ya0jOLRMcMUuHNLiWPTy591vnco=";
  47.  
  48. Console.WriteLine("javaSM2签名结果:" + javaSM2);
  49. byToProc = Convert.FromBase64String(javaSM2);
  50. //注意:JAVA HUTOOL - sm2.sign 结果格式是 asn1 的,我们得用 VerifySm3WithSm2Asn1Rs。
  51. verifySign = GmUtil.VerifySm3WithSm2Asn1Rs(Encoding.UTF8.GetBytes(javaContent), byUserId, byToProc, publicKey1);
  52.  
  53. Console.WriteLine("JAVA SM2 验签:" + verifySign.ToString());
  54. }

java代码:

maven 引用 :

  1. <dependency>
  2. <groupId>cn.hutool</groupId>
  3. <artifactId>hutool-all</artifactId>
  4. <version>5.8.1</version>
  5. </dependency>
  6.  
  7. <dependency>
  8. <groupId>org.bouncycastle</groupId>
  9. <artifactId>bcprov-jdk15on</artifactId>
  10. <version>1.70</version>
  11. </dependency>

JAVA调用:

  1. package org.example;
  2.  
  3. import cn.hutool.crypto.SmUtil;
  4. import cn.hutool.crypto.asymmetric.KeyType;
  5. import cn.hutool.crypto.asymmetric.SM2;
  6. import org.bouncycastle.crypto.engines.SM2Engine;
  7. import org.bouncycastle.util.encoders.Hex;
  8. import java.util.Base64;
  9.  
  10. static void testSM2Sign() {
  11.  
  12. String content = "1234泰酷拉JJ";
  13. System.out.println("待处理字符串:" + content);
  14. String userId = "1234567812345678";
  15. byte[] byUserId = userId.getBytes();
  16.  
  17. //私钥
  18. String privateKeyHex = "FAB8BBE670FAE338C9E9382B9FB6485225C11A3ECB84C938F10F20A93B6215F0";
  19. //公钥X
  20. String x = "9EF573019D9A03B16B0BE44FC8A5B4E8E098F56034C97B312282DD0B4810AFC3";
  21. //公钥Y
  22. String y = "CC759673ED0FC9B9DC7E6FA38F0E2B121E02654BF37EA6B63FAF2A0D6013EADF";
  23. //构造函数里,私钥或公钥,其中一方可为空 null
  24. SM2 sm2 = new SM2(privateKeyHex, x, y);
  25. byte[] byRst = sm2.sign(content.getBytes(), byUserId);
  26. String sm2Sign = Base64.getEncoder().encodeToString(byRst);
  27. System.out.println("sm2 BASE64 签名:" + sm2Sign);
  28.  
  29. byte[] bySign = Base64.getDecoder().decode(sm2Sign);
  30. boolean verifySign = sm2.verify(content.getBytes(), bySign, byUserId);
  31.  
  32. System.out.println("SM2 验签:" + verifySign);
  33. }

end

C#.NET 国密SM2 签名验签 与JAVA互通 ver:20230807的更多相关文章

  1. C#.NET 国密SM3withSM2签名与验签 和JAVA互通

    C# 基于.NET FRAMEWORK 4.5 JAVA 基于 JDK1.8 一.要点 1.签名算法:SM3withSM2. 2.签名值byte[] 转字符串时,双方要统一,这里是BASE64. 二. ...

  2. 谈谈PBOC3.0中使用的国密SM2算法

    转载请注明出处 http://blog.csdn.net/pony_maggie/article/details/39780825 作者:小马 一 知识准备 SM2是国密局推出的一种他们自己说具有自主 ...

  3. 推荐一款能支持国密SM2浏览器——密信浏览器

    密信浏览器( MeSince Browser )是基于Chromium开源项目开发的国密安全浏览器,支持国密算法和国密SSL证书,同时也支持国际算法及全球信任SSL证书:密信浏览器使用界面清新,干净. ...

  4. RSA签名验签

    import android.util.Base64; import java.security.KeyFactory; import java.security.PrivateKey; import ...

  5. 利用SHA-1算法和RSA秘钥进行签名验签(带注释)

    背景介绍 1.SHA 安全散列算法SHA (Secure Hash Algorithm)是美国国家标准和技术局发布的国家标准FIPS PUB 180-1,一般称为SHA-1.其对长度不超过264二进制 ...

  6. RSA密钥生成、加密解密、签名验签

    RSA 非对称加密公钥加密,私钥解密 私钥签名,公钥验签 下面是生成随机密钥对: //随机生成密钥对 KeyPairGenerator keyPairGen = null; try { keyPair ...

  7. C# RSACryptoServiceProvider加密解密签名验签和DESCryptoServic

    C#在using System.Security.Cryptography下有 DESCryptoServiceProvider RSACryptoServiceProvider DESCryptoS ...

  8. RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密

    原文:RSACryptoServiceProvider加密解密签名验签和DESCryptoServiceProvider加解密 C#在using System.Security.Cryptograph ...

  9. 数据安全管理:RSA加密算法,签名验签流程详解

    本文源码:GitHub·点这里 || GitEE·点这里 一.RSA算法简介 1.加密解密 RSA加密是一种非对称加密,在公开密钥加密和电子商业中RSA被广泛使用.可以在不直接传递密钥的情况下,完成加 ...

  10. js rsa sign使用笔记(加密,解密,签名,验签)

    你将会收获: js如何加密, 解密 js如何签名, 验签 js和Java交互如何相互解密, 验签(重点) 通过谷歌, 发现jsrsasign库使用者较多. 查看api发现这个库功能很健全. 本文使用方 ...

随机推荐

  1. C# 实现窗体启动时隐藏

    在某些时候需要实现一个界面的后台程序,程序自动运行,但起初不显示窗体,在满足触发条件时显示,此时需要在运行程序时先自动隐藏窗体. 修改窗体对应的Program.cs: using System; us ...

  2. Layui+dtree实现左边分类列表,右边数据列表

    效果如下 代码实现 <!DOCTYPE html> <html> <head> <meta charset="utf-8"> < ...

  3. 项目打包后配置到node服务器

    1.将项目进行打包 npm run build项目根目录下会多出一个打包好的由.js .html .css文件组成的dist文件夹,如图 2.搭建node微型服务器   新建文件夹命名"no ...

  4. 2022-08-19:以下go语言代码输出什么?A:equal;B:not equal;C:不确定。 package main import ( “fmt“ “reflect“ )

    2022-08-19:以下go语言代码输出什么?A:equal:B:not equal:C:不确定. package main import ( "fmt" "refle ...

  5. 2021-11-23:规定:L[1]对应a,L[2]对应b,L[3]对应c,...,L[25]对应y。 S1 = a, S(i) = S(i-1) + L[i] + reverse(invert(S(

    2021-11-23:规定:L[1]对应a,L[2]对应b,L[3]对应c,-,L[25]对应y. S1 = a, S(i) = S(i-1) + L[i] + reverse(invert(S(i- ...

  6. 详解RocketMQ 顺序消费机制

    摘要:顺序消息是指对于一个指定的 Topic ,消息严格按照先进先出(FIFO)的原则进行消息发布和消费,即先发布的消息先消费,后发布的消息后消费. 本文分享自华为云社区<RocketMQ 顺序 ...

  7. ShowMeBug 持续升级,提供高信效度支撑的技术招聘方案

    去年年底,全新升级版的 ShowMeBug --一款支持实战编程的技术能力评估平台,首次揭开了它神秘的面纱. 而近日,ShowMeBug 再次迎来一系列产品更新,它将以全新的面貌,提供高信效度支撑的技 ...

  8. Pytorch-如何在模型中引入可学习参数

    错误实例: def init(self): self.w1 = torch.nn.Parameter(torch.FloatTensor(1),requires_grad=True).cuda() s ...

  9. 【Photoshop】切图保存小坑(选择png格式得到gif问题)

    默认情况下:Photoshop 导出切片为[GIF]格式 当你很嗨皮的把[GIF]调整为[PNG]或[JPG]格式,并保存时: 你会发现,自己的图片格式莫名其妙还是[GIF]: 但,我们的期望是: 原 ...

  10. 【Unity3D】魔方

    1 需求实现 ​ 绘制魔方 中基于OpenGL ES 实现了魔方的绘制,实现较复杂,本文基于 Unity3D 实现了 2 ~ 10 阶魔方的整体旋转和局部旋转. ​ 本文完整代码资源见→基于 Unit ...