SMCipher.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using Org.BouncyCastle.Crypto;
  2. using Org.BouncyCastle.Crypto.Digests;
  3. using Org.BouncyCastle.Crypto.Generators;
  4. using Org.BouncyCastle.Crypto.Parameters;
  5. using Org.BouncyCastle.Math;
  6. using Org.BouncyCastle.Math.EC;
  7. using Org.BouncyCastle.Security;
  8. using Org.BouncyCastle.Utilities.Encoders;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Linq;
  12. using System.Text;
  13. using System.Threading.Tasks;
  14. namespace PTMedicalInsurance.Common
  15. {
  16. /// <summary>
  17. /// 密码计算
  18. /// </summary>
  19. public class Cipher
  20. {
  21. private int ct = 1;
  22. /// <summary>
  23. /// 椭圆曲线E上点P2
  24. /// </summary>
  25. private ECPoint p2;
  26. private SM3Digest sm3keybase;
  27. private SM3Digest sm3c3;
  28. private readonly byte[] key = new byte[32];
  29. private byte keyOff = 0;
  30. public Cipher()
  31. {
  32. }
  33. private void Reset()
  34. {
  35. sm3keybase = new SM3Digest();
  36. sm3c3 = new SM3Digest();
  37. byte[] p;
  38. p = p2.Normalize().XCoord.ToBigInteger().ToByteArray();
  39. sm3keybase.BlockUpdate(p, 0, p.Length);
  40. sm3c3.BlockUpdate(p, 0, p.Length);
  41. p = p2.Normalize().YCoord.ToBigInteger().ToByteArray();
  42. sm3keybase.BlockUpdate(p, 0, p.Length);
  43. ct = 1;
  44. NextKey();
  45. }
  46. private void NextKey()
  47. {
  48. SM3Digest sm3keycur = new SM3Digest(sm3keybase);
  49. sm3keycur.Update((byte)(ct >> 24 & 0x00ff));
  50. sm3keycur.Update((byte)(ct >> 16 & 0x00ff));
  51. sm3keycur.Update((byte)(ct >> 8 & 0x00ff));
  52. sm3keycur.Update((byte)(ct & 0x00ff));
  53. sm3keycur.DoFinal(key, 0);
  54. keyOff = 0;
  55. ct++;
  56. }
  57. public virtual ECPoint InitEnc(SM2 sm2, ECPoint userKey)
  58. {
  59. AsymmetricCipherKeyPair key = sm2.EccKeyPairGenerator.GenerateKeyPair();
  60. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
  61. ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
  62. BigInteger k = ecpriv.D;
  63. ECPoint c1 = ecpub.Q;
  64. p2 = userKey.Multiply(k);
  65. Reset();
  66. return c1;
  67. }
  68. public virtual void Encrypt(byte[] data)
  69. {
  70. //p2.Normalize();
  71. sm3c3.BlockUpdate(data, 0, data.Length);
  72. for (int i = 0; i < data.Length; i++)
  73. {
  74. if (keyOff == key.Length)
  75. NextKey();
  76. data[i] ^= key[keyOff++];
  77. }
  78. }
  79. public virtual void InitDec(BigInteger userD, ECPoint c1)
  80. {
  81. p2 = c1.Multiply(userD);
  82. Reset();
  83. }
  84. public virtual void Decrypt(byte[] data)
  85. {
  86. for (int i = 0; i < data.Length; i++)
  87. {
  88. if (keyOff == key.Length)
  89. NextKey();
  90. data[i] ^= key[keyOff++];
  91. }
  92. sm3c3.BlockUpdate(data, 0, data.Length);
  93. }
  94. public virtual void Dofinal(byte[] c3)
  95. {
  96. byte[] p = p2.Normalize().YCoord.ToBigInteger().ToByteArray();
  97. sm3c3.BlockUpdate(p, 0, p.Length);
  98. sm3c3.DoFinal(c3, 0);
  99. Reset();
  100. }
  101. }
  102. /// <summary>
  103. /// 加密处理中心
  104. /// </summary>
  105. public class SM2
  106. {
  107. public static SM2 Instance
  108. {
  109. get
  110. {
  111. return new SM2();
  112. }
  113. }
  114. public static SM2 InstanceTest
  115. {
  116. get
  117. {
  118. return new SM2();
  119. }
  120. }
  121. #region 曲线参数
  122. /// <summary>
  123. /// 曲线参数
  124. /// </summary>
  125. public static readonly string[] CurveParameter = {
  126. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF",// p,0
  127. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC",// a,1
  128. "28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93",// b,2
  129. "FFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123",// n,3
  130. "32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7",// gx,4
  131. "BC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0" // gy,5
  132. };
  133. /// <summary>
  134. /// 椭圆曲线参数
  135. /// </summary>
  136. public string[] EccParam = CurveParameter;
  137. /// <summary>
  138. /// 椭圆曲线参数P
  139. /// </summary>
  140. public readonly BigInteger EccP;
  141. /// <summary>
  142. /// 椭圆曲线参数A
  143. /// </summary>
  144. public readonly BigInteger EccA;
  145. /// <summary>
  146. /// 椭圆曲线参数B
  147. /// </summary>
  148. public readonly BigInteger EccB;
  149. /// <summary>
  150. /// 椭圆曲线参数N
  151. /// </summary>
  152. public readonly BigInteger EccN;
  153. /// <summary>
  154. /// 椭圆曲线参数Gx
  155. /// </summary>
  156. public readonly BigInteger EccGx;
  157. /// <summary>
  158. /// 椭圆曲线参数Gy
  159. /// </summary>
  160. public readonly BigInteger EccGy;
  161. #endregion
  162. /// <summary>
  163. /// 椭圆曲线
  164. /// </summary>
  165. public readonly ECCurve EccCurve;
  166. /// <summary>
  167. /// 椭圆曲线的点G
  168. /// </summary>
  169. public readonly ECPoint EccPointG;
  170. /// <summary>
  171. /// 椭圆曲线 bc规范
  172. /// </summary>
  173. public readonly ECDomainParameters EccBcSpec;
  174. /// <summary>
  175. /// 椭圆曲线密钥对生成器
  176. /// </summary>
  177. public readonly ECKeyPairGenerator EccKeyPairGenerator;
  178. private SM2()
  179. {
  180. EccParam = CurveParameter;
  181. EccP = new BigInteger(EccParam[0], 16);
  182. EccA = new BigInteger(EccParam[1], 16);
  183. EccB = new BigInteger(EccParam[2], 16);
  184. EccN = new BigInteger(EccParam[3], 16);
  185. EccGx = new BigInteger(EccParam[4], 16);
  186. EccGy = new BigInteger(EccParam[5], 16);
  187. ECFieldElement ecc_gx_fieldelement = new FpFieldElement(EccP, EccGx);
  188. ECFieldElement ecc_gy_fieldelement = new FpFieldElement(EccP, EccGy);
  189. EccCurve = new FpCurve(EccP, EccA, EccB);
  190. EccPointG = new FpPoint(EccCurve, ecc_gx_fieldelement, ecc_gy_fieldelement);
  191. EccBcSpec = new ECDomainParameters(EccCurve, EccPointG, EccN);
  192. ECKeyGenerationParameters ecc_ecgenparam;
  193. ecc_ecgenparam = new ECKeyGenerationParameters(EccBcSpec, new SecureRandom());
  194. EccKeyPairGenerator = new ECKeyPairGenerator();
  195. EccKeyPairGenerator.Init(ecc_ecgenparam);
  196. }
  197. /// <summary>
  198. /// 获取杂凑值H
  199. /// </summary>
  200. /// <param name="z">Z值</param>
  201. /// <param name="data">待签名消息</param>
  202. /// <returns></returns>
  203. public virtual byte[] Sm2GetH(byte[] z, byte[] data)
  204. {
  205. SM3Digest sm3 = new SM3Digest();
  206. //Z
  207. sm3.BlockUpdate(z, 0, z.Length);
  208. //待签名消息
  209. sm3.BlockUpdate(data, 0, data.Length);
  210. // H
  211. byte[] md = new byte[sm3.GetDigestSize()];
  212. sm3.DoFinal(md, 0);
  213. return md;
  214. }
  215. /// <summary>
  216. /// 获取Z值
  217. /// Z=SM3(ENTL∣∣userId∣∣a∣∣b∣∣gx∣∣gy ∣∣x∣∣y)
  218. /// </summary>
  219. /// <param name="userId">签名方的用户身份标识</param>
  220. /// <param name="userKey">签名方公钥</param>
  221. /// <returns></returns>
  222. public virtual byte[] Sm2GetZ(byte[] userId, ECPoint userKey)
  223. {
  224. SM3Digest sm3 = new SM3Digest();
  225. byte[] p;
  226. // ENTL由2个字节标识的ID的比特长度
  227. int len = userId.Length * 8;
  228. sm3.Update((byte)(len >> 8 & 0x00ff));
  229. sm3.Update((byte)(len & 0x00ff));
  230. // userId用户身份标识ID
  231. sm3.BlockUpdate(userId, 0, userId.Length);
  232. // a,b为系统曲线参数;
  233. p = EccA.ToByteArray();
  234. sm3.BlockUpdate(p, 0, p.Length);
  235. p = EccB.ToByteArray();
  236. sm3.BlockUpdate(p, 0, p.Length);
  237. // gx、gy为基点
  238. p = EccGx.ToByteArray();
  239. sm3.BlockUpdate(p, 0, p.Length);
  240. p = EccGy.ToByteArray();
  241. sm3.BlockUpdate(p, 0, p.Length);
  242. // x,y用户的公钥的X和Y
  243. p = userKey.Normalize().XCoord.ToBigInteger().ToByteArray();
  244. sm3.BlockUpdate(p, 0, p.Length);
  245. p = userKey.Normalize().YCoord.ToBigInteger().ToByteArray();
  246. sm3.BlockUpdate(p, 0, p.Length);
  247. // Z
  248. byte[] md = new byte[sm3.GetDigestSize()];
  249. sm3.DoFinal(md, 0);
  250. return md;
  251. }
  252. }
  253. /// <summary>
  254. /// Sm2算法
  255. /// 对标国际RSA算法
  256. /// </summary>
  257. public class Sm2Crypto
  258. {
  259. /// <summary>
  260. /// 数据
  261. /// </summary>
  262. public string Str { get; set; }
  263. /// <summary>
  264. /// 数据
  265. /// </summary>
  266. public byte[] Data { get; set; }
  267. /// <summary>
  268. /// 公钥
  269. /// </summary>
  270. public string PublicKey { get; set; }
  271. /// <summary>
  272. /// 私钥
  273. /// </summary>
  274. public string PrivateKey { get; set; }
  275. /// <summary>
  276. /// 获取密钥
  277. /// </summary>
  278. /// <param name="privateKey">私钥</param>
  279. /// <param name="publicKey">公钥</param>
  280. public static void GetKey(out string privateKey, out string publicKey)
  281. {
  282. SM2 sm2 = SM2.Instance;
  283. AsymmetricCipherKeyPair key = sm2.EccKeyPairGenerator.GenerateKeyPair();
  284. ECPrivateKeyParameters ecpriv = (ECPrivateKeyParameters)key.Private;
  285. ECPublicKeyParameters ecpub = (ECPublicKeyParameters)key.Public;
  286. publicKey = Encoding.Default.GetString(Hex.Encode(ecpub.Q.GetEncoded())).ToUpper();
  287. privateKey = Encoding.Default.GetString(Hex.Encode(ecpriv.D.ToByteArray())).ToUpper();
  288. }
  289. #region 解密
  290. public object Decrypt(Sm2Crypto entity)
  291. {
  292. var data = !string.IsNullOrEmpty(entity.Str) ?
  293. Hex.Decode(entity.Str) :
  294. entity.Data;
  295. return Encoding.Default.GetString(Decrypt(Hex.Decode(entity.PrivateKey), data));
  296. }
  297. /// <summary>
  298. /// 解密
  299. /// </summary>
  300. /// <param name="privateKey"></param>
  301. /// <param name="encryptedData"></param>
  302. /// <returns></returns>
  303. private static byte[] Decrypt(byte[] privateKey, byte[] encryptedData)
  304. {
  305. if (null == privateKey || privateKey.Length == 0)
  306. {
  307. return null;
  308. }
  309. if (encryptedData == null || encryptedData.Length == 0)
  310. {
  311. return null;
  312. }
  313. String data = Encoding.Default.GetString(Hex.Encode(encryptedData));
  314. byte[] c1Bytes = Hex.Decode(Encoding.Default.GetBytes(data.Substring(0, 130)));
  315. int c2Len = encryptedData.Length - 97;
  316. byte[] c2 = Hex.Decode(Encoding.Default.GetBytes(data.Substring(130, 2 * c2Len)));
  317. byte[] c3 = Hex.Decode(Encoding.Default.GetBytes(data.Substring(130 + 2 * c2Len, 64)));
  318. SM2 sm2 = SM2.Instance;
  319. BigInteger userD = new BigInteger(1, privateKey);
  320. ECPoint c1 = sm2.EccCurve.DecodePoint(c1Bytes);
  321. //c1.Normalize();
  322. Cipher cipher = new Cipher();
  323. cipher.InitDec(userD, c1);
  324. cipher.Decrypt(c2);
  325. cipher.Dofinal(c3);
  326. return c2;
  327. }
  328. #endregion
  329. #region 加密
  330. public string Encrypt(Sm2Crypto entity)
  331. {
  332. var data = !string.IsNullOrEmpty(entity.Str) ?
  333. Encoding.Default.GetBytes(entity.Str) :
  334. entity.Data;
  335. return Encrypt(Hex.Decode(entity.PublicKey), data);
  336. }
  337. /// <summary>
  338. /// 默认加密
  339. /// </summary>
  340. /// <returns></returns>
  341. public string Encrypt()
  342. {
  343. var data = !string.IsNullOrEmpty(this.Str) ?
  344. Encoding.Default.GetBytes(this.Str) :
  345. this.Data;
  346. return Encrypt(Hex.Decode(this.PublicKey), data);
  347. }
  348. /// <summary>
  349. /// 加密
  350. /// </summary>
  351. /// <param name="publicKey"></param>
  352. /// <param name="data"></param>
  353. /// <returns></returns>
  354. private static string Encrypt(byte[] publicKey, byte[] data)
  355. {
  356. if (null == publicKey || publicKey.Length == 0)
  357. {
  358. return null;
  359. }
  360. if (data == null || data.Length == 0)
  361. {
  362. return null;
  363. }
  364. byte[] source = new byte[data.Length];
  365. Array.Copy(data, 0, source, 0, data.Length);
  366. Cipher cipher = new Cipher();
  367. SM2 sm2 = SM2.Instance;
  368. ECPoint userKey = sm2.EccCurve.DecodePoint(publicKey);
  369. //userKey.Normalize();
  370. ECPoint c1 = cipher.InitEnc(sm2, userKey);
  371. cipher.Encrypt(source);
  372. byte[] c3 = new byte[32];
  373. cipher.Dofinal(c3);
  374. String sc1 = Encoding.Default.GetString(Hex.Encode(c1.GetEncoded()));
  375. String sc2 = Encoding.Default.GetString(Hex.Encode(source));
  376. String sc3 = Encoding.Default.GetString(Hex.Encode(c3));
  377. return (sc1 + sc2 + sc3).ToUpper();
  378. }
  379. #endregion
  380. }
  381. }