当前位置:   article > 正文

C#.NET 国密数字信封 民生银行_c# sm3withsm2

c# sm3withsm2

民生银行的库DLL只有C版本和JAVA版本。按着JAVA版本做的C# 实现。

重点内容。

1。数字信封就是 CmsEnvelopedData Der编码后转BASE64

2。重点类:ContentInfo、EnvelopedData、EncryptedContentInfo、RecipientInfo。

3。随机生成 SM4 key和IV,都是16位。其中:SM4 key 使用SM2加密后,放入RecipientInfo。

4。IV 使用 DerOctetString 编码后,使用 AlgorithmIdentifier 携带。

5。把待加密数据用SM4 CBC 加密,Ber编码后放入 EncryptedContentInfo。

6。CmsEnvelopedData 包含 ContentInfo、EnvelopedData、EncryptedContentInfo、RecipientInfo。

7。SM2加密后,密文会是 04 开头,要去掉后传给JAVA(民生)。

实现:

nuget 下载 BouncyCastle,1.8.9 版本。

GmUtil:

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

国密数字信封加密:

  1. using CommonUtils;
  2. using Org.BouncyCastle.Asn1;
  3. using Org.BouncyCastle.Asn1.Cms;
  4. using Org.BouncyCastle.Asn1.X509;
  5. using Org.BouncyCastle.Cms;
  6. using Org.BouncyCastle.Crypto;
  7. using Org.BouncyCastle.Math;
  8. using Org.BouncyCastle.Utilities.Encoders;
  9. using System;
  10. using System.IO;
  11. using System.Text;
  12. namespace Console民生银行国密数字信封
  13. {
  14. internal class Program
  15. {
  16. static void Main(string[] args)
  17. {
  18. try
  19. {
  20. //国密公钥证书
  21. string txtIsvPubCert = "MIICuzCCAl6gAwIBAgIFMAU2UREwDAYIKoEcz1UBg3UFADArMQswCQYDVQQGEwJDTjEcMBoGA1UECgwTQ0ZDQSBTTTIgVEVTVCBPQ0EyMTAeFw0yMDA1MTQxMDQ5MjNaFw0yMTA1MTQxMDQ5MjNaMHExCzAJBgNVBAYTAkNOMQ0wCwYDVQQKDARDTUJDMRIwEAYDVQQLDAlDTUJDX0RDTVMxGTAXBgNVBAsMEE9yZ2FuaXphdGlvbmFsLTExJDAiBgNVBAMMGzAzMDVAWjEyMzMyMjMxQDYzODA1MTQwMDFAMTBZMBMGByqGSM49AgEGCCqBHM9VAYItA0IABEnvYQ89A2eFUsEvhfik13ehN1vNivpfk3UTCOPp209UbwLlatSu1aBFerNeNB6FQ9dgSSaXCiSMUfgKKL9wpBWjggElMIIBITAfBgNVHSMEGDAWgBTifrYQu5TrFeau0RUK/+jXoFc5nTBIBgNVHSAEQTA/MD0GCGCBHIbvKgICMDEwLwYIKwYBBQUHAgEWI2h0dHA6Ly93d3cuY2ZjYS5jb20uY24vdXMvdXMtMTMuaHRtMGkGA1UdHwRiMGAwLqAsoCqGKGh0dHA6Ly8yMTAuNzQuNDIuMy9PQ0EyMS9TTTIvY3JsMzE1Ni5jcmwwLqAsoCqGKGh0dHA6Ly8yMTAuNzQuNDIuMy9PQ0EyMS9TTTIvY3JsMzE1Ni5jcmwwCwYDVR0PBAQDAgP4MB0GA1UdDgQWBBRXXvBVVWTiR6ARshCGukqaGyUKfzAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwDAYIKoEcz1UBg3UFAANJADBGAiEA7O5rAx4+Alx2eIq0CHxTrNrQIOmphxShur4JDMwLiEYCIQDpJD/z85jWcwUeRAOOcstm4Ppl5zKu6pPohnbKm7gqvg==";
  22. //国密私钥证书
  23. string gmPrivateKeyCert = @"MIIDHwIBATBHBgoqgRzPVQYBBAIBBgcqgRzPVQFoBDBgkpL4SzxKcmNmrzvEtrl5lncqsy/fvW/6
  24. uKSe2Wa5x0NeIcRuohTMdQIYd6rXsOAwggLPBgoqgRzPVQYBBAIBBIICvzCCArswggJeoAMCAQIC
  25. BTAFNlERMAwGCCqBHM9VAYN1BQAwKzELMAkGA1UEBhMCQ04xHDAaBgNVBAoME0NGQ0EgU00yIFRF
  26. U1QgT0NBMjEwHhcNMjAwNTE0MTA0OTIzWhcNMjEwNTE0MTA0OTIzWjBxMQswCQYDVQQGEwJDTjEN
  27. MAsGA1UECgwEQ01CQzESMBAGA1UECwwJQ01CQ19EQ01TMRkwFwYDVQQLDBBPcmdhbml6YXRpb25h
  28. bC0xMSQwIgYDVQQDDBswMzA1QFoxMjMzMjIzMUA2MzgwNTE0MDAxQDEwWTATBgcqhkjOPQIBBggq
  29. gRzPVQGCLQNCAARJ72EPPQNnhVLBL4X4pNd3oTdbzYr6X5N1Ewjj6dtPVG8C5WrUrtWgRXqzXjQe
  30. hUPXYEkmlwokjFH4Cii/cKQVo4IBJTCCASEwHwYDVR0jBBgwFoAU4n62ELuU6xXmrtEVCv/o16BX
  31. OZ0wSAYDVR0gBEEwPzA9BghggRyG7yoCAjAxMC8GCCsGAQUFBwIBFiNodHRwOi8vd3d3LmNmY2Eu
  32. Y29tLmNuL3VzL3VzLTEzLmh0bTBpBgNVHR8EYjBgMC6gLKAqhihodHRwOi8vMjEwLjc0LjQyLjMv
  33. T0NBMjEvU00yL2NybDMxNTYuY3JsMC6gLKAqhihodHRwOi8vMjEwLjc0LjQyLjMvT0NBMjEvU00y
  34. L2NybDMxNTYuY3JsMAsGA1UdDwQEAwID+DAdBgNVHQ4EFgQUV17wVVVk4kegEbIQhrpKmhslCn8w
  35. HQYDVR0lBBYwFAYIKwYBBQUHAwIGCCsGAQUFBwMEMAwGCCqBHM9VAYN1BQADSQAwRgIhAOzuawMe
  36. PgJcdniKtAh8U6za0CDpqYcUobq+CQzMC4hGAiEA6SQ/8/OY1nMFHkQDjnLLZuD6ZecyruqT6IZ2
  37. ypu4Kr4=";
  38. //国密私钥证书密码
  39. string gmPrivateKeyCertPwd = "123abc";
  40. string inputStr = "oh yeah 123。";
  41. Console.WriteLine("数字信封-待加密数据:" + inputStr);
  42. var aa = CmsEncrypt(inputStr, txtIsvPubCert);
  43. Console.WriteLine("数字信封-加密数据:" + aa);
  44. //测试JAVA程序加密结果
  45. // aa = "MIIBdgYKKoEcz1UGAQQCA6CCAWYwggFiAgECMYGdMIGaAgECgBRXXvBVVWTiR6ARshCGukqaGyUKfzANBgkqgRzPVQGCLQMFAARwV3Je52JbokQWyl7uD2GDuWtkyzIzn8nsE2uX2XthHTwnoB+WtLkemKjs+iUJl5EShTgUI2g5N6Uw3/4QN9/LHETixsQ/Emv3hW9W3V2ERNJiu9Hd/raPN+zIyWhraEU6oXTvpwfFgNoVjbp9U9UbHjCBvAYKKoEcz1UGAQQCATAbBgcqgRzPVQFoBBArCB1Z2eO/rLl1Xdn9MMIOgIGQKNpS0jslyLvneyGs2xI2Rz4dLiEznOeXt8JjuEo08vKNf0JOpxFIK9q8X8oCE/NCBjwSmZ38ZwauUydQE+3zQUiInqIOPV8+w+1ejmi4LyWTeDuWtYUESw7qfmG7oxd6hvIM3pswNXXxOEjfmH/7cS8iHCzRg2fli0smDOREil8lPjUM68lTZ9xgcsq4a8+2";
  46. // Console.WriteLine("数字信封-加密数据:" + aa);
  47. var bb = CmsDecrypt(aa, gmPrivateKeyCert, gmPrivateKeyCertPwd);
  48. Console.WriteLine("数字信封-解密数据:" + bb);
  49. }
  50. catch (Exception ex)
  51. {
  52. Console.WriteLine("ex:" + ex.Message);
  53. }
  54. Console.ReadKey();
  55. }
  56. /// <summary>
  57. /// 数字信封-加密
  58. /// </summary>
  59. static string CmsEncrypt(string inputStr, string pubkeyCert)
  60. {
  61. //SM2,SM4 加密数据从 string 转 byte 数组时,使用UTF8。
  62. Encoding enc = Encoding.UTF8;
  63. //调试时可以写死KEY和IV
  64. //string sm4key = "1234567890123456";
  65. //string sm4iv = "1234567890123456";
  66. //随机生成KEY和IV,都是16字符长度
  67. string sm4key = Guid.NewGuid().ToString("N").Substring(0, 16);
  68. string sm4iv = Guid.NewGuid().ToString("N").Substring(0, 16);
  69. //如果是 NoPadding, SM4 加密的数据(byte[] plain)得是16的倍数
  70. string algo = "SM4/CBC/PKCS7Padding";
  71. byte[] keyBytes = Encoding.UTF8.GetBytes(sm4key);
  72. byte[] ivBytes = Encoding.UTF8.GetBytes(sm4iv);
  73. #region 使用SM2加密SM4 KEY
  74. AsymmetricKeyParameter bankPubCert2 = GmUtil.GetPublickeyFromX509String(pubkeyCert);
  75. byte[] bytencryptedData = enc.GetBytes(sm4key);
  76. byte[] bysm4keyEncrypted = GmUtil.Sm2EncryptOld(bytencryptedData, bankPubCert2);//使用SM2加密SM4 KEY
  77. //BC库SM2加密结果会带04,删除加密结果前的04,否则JAVA(民生银行) 那边解密不了。Invalid point encoding
  78. string newCipherText = Hex.ToHexString(bysm4keyEncrypted);
  79. if (newCipherText.StartsWith("04"))
  80. {
  81. newCipherText = newCipherText.Substring(2);
  82. }
  83. bysm4keyEncrypted = Hex.Decode(newCipherText);
  84. // 主题密钥标识符 (SKI)。 JAVA BC 库写法:SubjectKeyIdentifier sid = cert.getSubjectKeyIdentifier();
  85. SubjectKeyIdentifier sid = new Org.BouncyCastle.X509.Extension.SubjectKeyIdentifierStructure(bankPubCert2);
  86. #endregion
  87. Asn1OctetString encKey = new DerOctetString(bysm4keyEncrypted);
  88. AlgorithmIdentifier keyEncAlg = new AlgorithmIdentifier(new DerObjectIdentifier("1.2.156.10197.1.301.3")); //sm2 公钥加密算法ID
  89. KeyTransRecipientInfo ktr = new KeyTransRecipientInfo(new RecipientIdentifier(new DerOctetString(sid.GetKeyIdentifier())), keyEncAlg, encKey);
  90. RecipientInfo ri = new RecipientInfo(ktr); //SM4 key 使用SM2加密后,放入RecipientInfo。
  91. byte[] sourceData = enc.GetBytes(inputStr);
  92. byte[] encryptedData = GmUtil.Sm4EncryptCBC(keyBytes, sourceData, ivBytes, algo); ;//待SM4 加密,加密后的数据
  93. DerObjectIdentifier sm2DataID = new DerObjectIdentifier("1.2.156.10197.6.1.4.2.1");//SM2数据类型data ID
  94. DerOctetString doct = new DerOctetString(ivBytes);
  95. DerObjectIdentifier tOID = new DerObjectIdentifier("1.2.156.10197.1.104"); // SM4_CBC ,ID
  96. AlgorithmIdentifier contentEncryptionAlgId = new AlgorithmIdentifier(tOID, doct);//用 AlgorithmIdentifier携带 IV 数据
  97. Asn1EncodableVector recipientInfos = new Asn1EncodableVector();
  98. recipientInfos.Add(ri);//SM4 key 使用SM2加密后,放入RecipientInfo。
  99. Asn1Set aSet1 = null;
  100. Asn1OctetString encryptOctet = new BerOctetString(encryptedData);//SM4加密后的数据
  101. EncryptedContentInfo eci = new EncryptedContentInfo(sm2DataID, contentEncryptionAlgId, encryptOctet);// SM4-IV 和 SM4加密后的数据
  102. EnvelopedData enData = new EnvelopedData(null, new DerSet(recipientInfos), eci, aSet1);// SM4-KEY,SM4-IV 和 SM4加密后的数据
  103. DerObjectIdentifier sm2EnvelopedDataID = new DerObjectIdentifier("1.2.156.10197.6.1.4.2.3");//数字信封数据类型envelopedData ID
  104. ContentInfo contentInfo = new ContentInfo(sm2EnvelopedDataID, enData);
  105. string base64CmsEncryptData = string.Empty;
  106. using (MemoryStream bos = new MemoryStream())
  107. {
  108. using (DerOutputStream dos = new DerOutputStream(bos))
  109. {
  110. dos.WriteObject((new CmsEnvelopedData(contentInfo)).ContentInfo);
  111. byte[] byteArray = bos.ToArray();
  112. base64CmsEncryptData = Convert.ToBase64String(byteArray);
  113. }
  114. }
  115. return base64CmsEncryptData;
  116. }
  117. /// <summary>
  118. /// 数字信封-解密
  119. /// </summary>
  120. static string CmsDecrypt(string cmsEnvelopedData, string gmPrivateKeyCert, string gmPrivateKeyCertPwd)
  121. {
  122. //获取私钥对象 AsymmetricKeyParameter privateKey
  123. var pemPrivateKey = Convert.FromBase64String(gmPrivateKeyCert);
  124. var tempPrivateKey = GmUtil.readSm2File(pemPrivateKey, gmPrivateKeyCertPwd);
  125. AsymmetricKeyParameter privateKey = tempPrivateKey.privateKey;
  126. byte[] bEnvelop = Convert.FromBase64String(cmsEnvelopedData);
  127. CmsEnvelopedData cmsEnData = new CmsEnvelopedData(bEnvelop);
  128. ContentInfo info = cmsEnData.ContentInfo;
  129. EnvelopedData enData = EnvelopedData.GetInstance(info.Content);
  130. Asn1Set receivers = enData.RecipientInfos;
  131. #region 使用SM2 私钥解密出SM4 KEY
  132. //没适配多receivers的情况,强取第1个
  133. RecipientInfo recipientInfo = RecipientInfo.GetInstance(receivers[0]);
  134. KeyTransRecipientInfo keyTransRecipientInfo = KeyTransRecipientInfo.GetInstance(recipientInfo.Info);
  135. Asn1OctetString encryptKey = keyTransRecipientInfo.EncryptedKey;
  136. AlgorithmIdentifier algId = keyTransRecipientInfo.KeyEncryptionAlgorithm;
  137. byte[] byEncryptKey = encryptKey.GetOctets();
  138. string hexEncryptKey = Hex.ToHexString(byEncryptKey);
  139. //BC库解密,密文前要加 “04”,否则会报 Invalid point encoding XX
  140. if (!hexEncryptKey.StartsWith("04"))
  141. {
  142. hexEncryptKey = "04" + hexEncryptKey;
  143. }
  144. byEncryptKey = Hex.Decode(hexEncryptKey);
  145. byte[] symmetricKey = GmUtil.Sm2DecryptOld(byEncryptKey, privateKey);
  146. #endregion
  147. #region 拿到 SM4 IV
  148. //拿到 SM4 IV
  149. EncryptedContentInfo data = enData.EncryptedContentInfo;
  150. AlgorithmIdentifier symmetricAlgId = data.ContentEncryptionAlgorithm;
  151. DerOctetString doct = (DerOctetString)symmetricAlgId.Parameters;
  152. byte[] bySm4Iv = doct.GetOctets();
  153. #endregion
  154. //取出被SM4加密的数据
  155. string algo = "SM4/CBC/PKCS7Padding";
  156. byte[] encryptedBytes = data.EncryptedContent.GetOctets();
  157. byte[] sourceData = GmUtil.Sm4DecryptCBC(symmetricKey, encryptedBytes, bySm4Iv, algo);
  158. string sm4DecryptedStr = Encoding.UTF8.GetString(sourceData);//偷懒,写死了UTF8。
  159. return sm4DecryptedStr;
  160. }
  161. }
  162. }

end

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/787096
推荐阅读
相关标签
  

闽ICP备14008679号