SMCipher.cs 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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 AnHuiMI.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. class SM4
  382. {
  383. public const int SM4_ENCRYPT = 1;
  384. public const int SM4_DECRYPT = 0;
  385. private long GET_ULONG_BE(byte[] b, int i)
  386. {
  387. long n = (long)(b[i] & 0xff) << 24 | (long)((b[i + 1] & 0xff) << 16) | (long)((b[i + 2] & 0xff) << 8) | (long)(b[i + 3] & 0xff) & 0xffffffffL;
  388. return n;
  389. }
  390. private void PUT_ULONG_BE(long n, byte[] b, int i)
  391. {
  392. b[i] = (byte)(int)(0xFF & n >> 24);
  393. b[i + 1] = (byte)(int)(0xFF & n >> 16);
  394. b[i + 2] = (byte)(int)(0xFF & n >> 8);
  395. b[i + 3] = (byte)(int)(0xFF & n);
  396. }
  397. private long SHL(long x, int n)
  398. {
  399. return (x & 0xFFFFFFFF) << n;
  400. }
  401. private long ROTL(long x, int n)
  402. {
  403. return SHL(x, n) | x >> (32 - n);
  404. }
  405. private void SWAP(long[] sk, int i)
  406. {
  407. long t = sk[i];
  408. sk[i] = sk[(31 - i)];
  409. sk[(31 - i)] = t;
  410. }
  411. public byte[] SboxTable = new byte[] { (byte) 0xd6, (byte) 0x90, (byte) 0xe9, (byte) 0xfe,
  412. (byte) 0xcc, (byte) 0xe1, 0x3d, (byte) 0xb7, 0x16, (byte) 0xb6,
  413. 0x14, (byte) 0xc2, 0x28, (byte) 0xfb, 0x2c, 0x05, 0x2b, 0x67,
  414. (byte) 0x9a, 0x76, 0x2a, (byte) 0xbe, 0x04, (byte) 0xc3,
  415. (byte) 0xaa, 0x44, 0x13, 0x26, 0x49, (byte) 0x86, 0x06,
  416. (byte) 0x99, (byte) 0x9c, 0x42, 0x50, (byte) 0xf4, (byte) 0x91,
  417. (byte) 0xef, (byte) 0x98, 0x7a, 0x33, 0x54, 0x0b, 0x43,
  418. (byte) 0xed, (byte) 0xcf, (byte) 0xac, 0x62, (byte) 0xe4,
  419. (byte) 0xb3, 0x1c, (byte) 0xa9, (byte) 0xc9, 0x08, (byte) 0xe8,
  420. (byte) 0x95, (byte) 0x80, (byte) 0xdf, (byte) 0x94, (byte) 0xfa,
  421. 0x75, (byte) 0x8f, 0x3f, (byte) 0xa6, 0x47, 0x07, (byte) 0xa7,
  422. (byte) 0xfc, (byte) 0xf3, 0x73, 0x17, (byte) 0xba, (byte) 0x83,
  423. 0x59, 0x3c, 0x19, (byte) 0xe6, (byte) 0x85, 0x4f, (byte) 0xa8,
  424. 0x68, 0x6b, (byte) 0x81, (byte) 0xb2, 0x71, 0x64, (byte) 0xda,
  425. (byte) 0x8b, (byte) 0xf8, (byte) 0xeb, 0x0f, 0x4b, 0x70, 0x56,
  426. (byte) 0x9d, 0x35, 0x1e, 0x24, 0x0e, 0x5e, 0x63, 0x58, (byte) 0xd1,
  427. (byte) 0xa2, 0x25, 0x22, 0x7c, 0x3b, 0x01, 0x21, 0x78, (byte) 0x87,
  428. (byte) 0xd4, 0x00, 0x46, 0x57, (byte) 0x9f, (byte) 0xd3, 0x27,
  429. 0x52, 0x4c, 0x36, 0x02, (byte) 0xe7, (byte) 0xa0, (byte) 0xc4,
  430. (byte) 0xc8, (byte) 0x9e, (byte) 0xea, (byte) 0xbf, (byte) 0x8a,
  431. (byte) 0xd2, 0x40, (byte) 0xc7, 0x38, (byte) 0xb5, (byte) 0xa3,
  432. (byte) 0xf7, (byte) 0xf2, (byte) 0xce, (byte) 0xf9, 0x61, 0x15,
  433. (byte) 0xa1, (byte) 0xe0, (byte) 0xae, 0x5d, (byte) 0xa4,
  434. (byte) 0x9b, 0x34, 0x1a, 0x55, (byte) 0xad, (byte) 0x93, 0x32,
  435. 0x30, (byte) 0xf5, (byte) 0x8c, (byte) 0xb1, (byte) 0xe3, 0x1d,
  436. (byte) 0xf6, (byte) 0xe2, 0x2e, (byte) 0x82, 0x66, (byte) 0xca,
  437. 0x60, (byte) 0xc0, 0x29, 0x23, (byte) 0xab, 0x0d, 0x53, 0x4e, 0x6f,
  438. (byte) 0xd5, (byte) 0xdb, 0x37, 0x45, (byte) 0xde, (byte) 0xfd,
  439. (byte) 0x8e, 0x2f, 0x03, (byte) 0xff, 0x6a, 0x72, 0x6d, 0x6c, 0x5b,
  440. 0x51, (byte) 0x8d, 0x1b, (byte) 0xaf, (byte) 0x92, (byte) 0xbb,
  441. (byte) 0xdd, (byte) 0xbc, 0x7f, 0x11, (byte) 0xd9, 0x5c, 0x41,
  442. 0x1f, 0x10, 0x5a, (byte) 0xd8, 0x0a, (byte) 0xc1, 0x31,
  443. (byte) 0x88, (byte) 0xa5, (byte) 0xcd, 0x7b, (byte) 0xbd, 0x2d,
  444. 0x74, (byte) 0xd0, 0x12, (byte) 0xb8, (byte) 0xe5, (byte) 0xb4,
  445. (byte) 0xb0, (byte) 0x89, 0x69, (byte) 0x97, 0x4a, 0x0c,
  446. (byte) 0x96, 0x77, 0x7e, 0x65, (byte) 0xb9, (byte) 0xf1, 0x09,
  447. (byte) 0xc5, 0x6e, (byte) 0xc6, (byte) 0x84, 0x18, (byte) 0xf0,
  448. 0x7d, (byte) 0xec, 0x3a, (byte) 0xdc, 0x4d, 0x20, 0x79,
  449. (byte) 0xee, 0x5f, 0x3e, (byte) 0xd7, (byte) 0xcb, 0x39, 0x48 };
  450. public uint[] FK = { 0xa3b1bac6, 0x56aa3350, 0x677d9197, 0xb27022dc };
  451. public uint[] CK = { 0x00070e15,0x1c232a31,0x383f464d,0x545b6269,
  452. 0x70777e85,0x8c939aa1,0xa8afb6bd,0xc4cbd2d9,
  453. 0xe0e7eef5,0xfc030a11,0x181f262d,0x343b4249,
  454. 0x50575e65,0x6c737a81,0x888f969d,0xa4abb2b9,
  455. 0xc0c7ced5,0xdce3eaf1,0xf8ff060d,0x141b2229,
  456. 0x30373e45,0x4c535a61,0x686f767d,0x848b9299,
  457. 0xa0a7aeb5,0xbcc3cad1,0xd8dfe6ed,0xf4fb0209,
  458. 0x10171e25,0x2c333a41,0x484f565d,0x646b7279 };
  459. private byte sm4Sbox(byte inch)
  460. {
  461. int i = inch & 0xFF;
  462. byte retVal = SboxTable[i];
  463. return retVal;
  464. }
  465. private long sm4Lt(long ka)
  466. {
  467. long bb = 0L;
  468. long c = 0L;
  469. byte[] a = new byte[4];
  470. byte[] b = new byte[4];
  471. PUT_ULONG_BE(ka, a, 0);
  472. b[0] = sm4Sbox(a[0]);
  473. b[1] = sm4Sbox(a[1]);
  474. b[2] = sm4Sbox(a[2]);
  475. b[3] = sm4Sbox(a[3]);
  476. bb = GET_ULONG_BE(b, 0);
  477. c = bb ^ ROTL(bb, 2) ^ ROTL(bb, 10) ^ ROTL(bb, 18) ^ ROTL(bb, 24);
  478. return c;
  479. }
  480. private long sm4F(long x0, long x1, long x2, long x3, long rk)
  481. {
  482. return x0 ^ sm4Lt(x1 ^ x2 ^ x3 ^ rk);
  483. }
  484. private long sm4CalciRK(long ka)
  485. {
  486. long bb = 0L;
  487. long rk = 0L;
  488. byte[] a = new byte[4];
  489. byte[] b = new byte[4];
  490. PUT_ULONG_BE(ka, a, 0);
  491. b[0] = sm4Sbox(a[0]);
  492. b[1] = sm4Sbox(a[1]);
  493. b[2] = sm4Sbox(a[2]);
  494. b[3] = sm4Sbox(a[3]);
  495. bb = GET_ULONG_BE(b, 0);
  496. rk = bb ^ ROTL(bb, 13) ^ ROTL(bb, 23);
  497. return rk;
  498. }
  499. private void sm4_setkey(long[] SK, byte[] key)
  500. {
  501. long[] MK = new long[4];
  502. long[] k = new long[36];
  503. int i = 0;
  504. MK[0] = GET_ULONG_BE(key, 0);
  505. MK[1] = GET_ULONG_BE(key, 4);
  506. MK[2] = GET_ULONG_BE(key, 8);
  507. MK[3] = GET_ULONG_BE(key, 12);
  508. k[0] = MK[0] ^ (long)FK[0];
  509. k[1] = MK[1] ^ (long)FK[1];
  510. k[2] = MK[2] ^ (long)FK[2];
  511. k[3] = MK[3] ^ (long)FK[3];
  512. for (; i < 32; i++)
  513. {
  514. k[(i + 4)] = (k[i] ^ sm4CalciRK(k[(i + 1)] ^ k[(i + 2)] ^ k[(i + 3)] ^ (long)CK[i]));
  515. SK[i] = k[(i + 4)];
  516. }
  517. }
  518. private void sm4_one_round(long[] sk, byte[] input, byte[] output)
  519. {
  520. int i = 0;
  521. long[] ulbuf = new long[36];
  522. ulbuf[0] = GET_ULONG_BE(input, 0);
  523. ulbuf[1] = GET_ULONG_BE(input, 4);
  524. ulbuf[2] = GET_ULONG_BE(input, 8);
  525. ulbuf[3] = GET_ULONG_BE(input, 12);
  526. while (i < 32)
  527. {
  528. ulbuf[(i + 4)] = sm4F(ulbuf[i], ulbuf[(i + 1)], ulbuf[(i + 2)], ulbuf[(i + 3)], sk[i]);
  529. i++;
  530. }
  531. PUT_ULONG_BE(ulbuf[35], output, 0);
  532. PUT_ULONG_BE(ulbuf[34], output, 4);
  533. PUT_ULONG_BE(ulbuf[33], output, 8);
  534. PUT_ULONG_BE(ulbuf[32], output, 12);
  535. }
  536. private byte[] padding(byte[] input, int mode)
  537. {
  538. if (input == null)
  539. {
  540. return null;
  541. }
  542. byte[] ret = (byte[])null;
  543. if (mode == SM4_ENCRYPT)
  544. {
  545. int p = 16 - input.Length % 16;
  546. ret = new byte[input.Length + p];
  547. Array.Copy(input, 0, ret, 0, input.Length);
  548. for (int i = 0; i < p; i++)
  549. {
  550. ret[input.Length + i] = (byte)p;
  551. }
  552. }
  553. else
  554. {
  555. int p = input[input.Length - 1];
  556. ret = new byte[input.Length - p];
  557. Array.Copy(input, 0, ret, 0, input.Length - p);
  558. }
  559. return ret;
  560. }
  561. public void sm4_setkey_enc(SM4_Context ctx, byte[] key)
  562. {
  563. ctx.mode = SM4_ENCRYPT;
  564. sm4_setkey(ctx.sk, key);
  565. }
  566. public void sm4_setkey_dec(SM4_Context ctx, byte[] key)
  567. {
  568. int i = 0;
  569. ctx.mode = SM4_DECRYPT;
  570. sm4_setkey(ctx.sk, key);
  571. for (i = 0; i < 16; i++)
  572. {
  573. SWAP(ctx.sk, i);
  574. }
  575. }
  576. public byte[] sm4_crypt_ecb(SM4_Context ctx, byte[] input)
  577. {
  578. if ((ctx.isPadding) && (ctx.mode == SM4_ENCRYPT))
  579. {
  580. input = padding(input, SM4_ENCRYPT);
  581. }
  582. int length = input.Length;
  583. byte[] bins = new byte[length];
  584. Array.Copy(input, 0, bins, 0, length);
  585. byte[] bous = new byte[length];
  586. for (int i = 0; length > 0; length -= 16, i++)
  587. {
  588. byte[] inBytes = new byte[16];
  589. byte[] outBytes = new byte[16];
  590. Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
  591. sm4_one_round(ctx.sk, inBytes, outBytes);
  592. Array.Copy(outBytes, 0, bous, i * 16, length > 16 ? 16 : length);
  593. }
  594. if (ctx.isPadding && ctx.mode == SM4_DECRYPT)
  595. {
  596. bous = padding(bous, SM4_DECRYPT);
  597. }
  598. return bous;
  599. }
  600. public byte[] sm4_crypt_cbc(SM4_Context ctx, byte[] iv, byte[] input)
  601. {
  602. if (ctx.isPadding && ctx.mode == SM4_ENCRYPT)
  603. {
  604. input = padding(input, SM4_ENCRYPT);
  605. }
  606. int i = 0;
  607. int length = input.Length;
  608. byte[] bins = new byte[length];
  609. Array.Copy(input, 0, bins, 0, length);
  610. byte[] bous = null;
  611. List<byte> bousList = new List<byte>();
  612. if (ctx.mode == SM4_ENCRYPT)
  613. {
  614. for (int j = 0; length > 0; length -= 16, j++)
  615. {
  616. byte[] inBytes = new byte[16];
  617. byte[] outBytes = new byte[16];
  618. byte[] out1 = new byte[16];
  619. Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
  620. for (i = 0; i < 16; i++)
  621. {
  622. outBytes[i] = ((byte)(inBytes[i] ^ iv[i]));
  623. }
  624. sm4_one_round(ctx.sk, outBytes, out1);
  625. Array.Copy(out1, 0, iv, 0, 16);
  626. for (int k = 0; k < 16; k++)
  627. {
  628. bousList.Add(out1[k]);
  629. }
  630. }
  631. }
  632. else
  633. {
  634. byte[] temp = new byte[16];
  635. for (int j = 0; length > 0; length -= 16, j++)
  636. {
  637. byte[] inBytes = new byte[16];
  638. byte[] outBytes = new byte[16];
  639. byte[] out1 = new byte[16];
  640. Array.Copy(bins, i * 16, inBytes, 0, length > 16 ? 16 : length);
  641. Array.Copy(inBytes, 0, temp, 0, 16);
  642. sm4_one_round(ctx.sk, inBytes, outBytes);
  643. for (i = 0; i < 16; i++)
  644. {
  645. out1[i] = ((byte)(outBytes[i] ^ iv[i]));
  646. }
  647. Array.Copy(temp, 0, iv, 0, 16);
  648. for (int k = 0; k < 16; k++)
  649. {
  650. bousList.Add(out1[k]);
  651. }
  652. }
  653. }
  654. if (ctx.isPadding && ctx.mode == SM4_DECRYPT)
  655. {
  656. bous = padding(bousList.ToArray(), SM4_DECRYPT);
  657. return bous;
  658. }
  659. else
  660. {
  661. return bousList.ToArray();
  662. }
  663. }
  664. }
  665. class SM4_Context
  666. {
  667. public int mode;
  668. public long[] sk;
  669. public bool isPadding;
  670. public SM4_Context()
  671. {
  672. this.mode = 1;
  673. this.isPadding = true;
  674. this.sk = new long[32];
  675. }
  676. }
  677. class SM4Utils
  678. {
  679. public string secretKey = "";
  680. public string iv = "";
  681. public bool hexstring = false;
  682. public string Encrypt_ECB(string plainText,string key)
  683. {
  684. this.secretKey = key;
  685. return Encrypt_ECB(plainText);
  686. }
  687. public string Encrypt_ECB(string plainText)
  688. {
  689. SM4_Context ctx = new SM4_Context();
  690. ctx.isPadding = true;
  691. ctx.mode = SM4.SM4_ENCRYPT;
  692. byte[] keyBytes;
  693. if (hexstring)
  694. {
  695. keyBytes = Hex.Decode(secretKey);
  696. }
  697. else
  698. {
  699. keyBytes = Encoding.Default.GetBytes(secretKey);
  700. }
  701. SM4 sm4 = new SM4();
  702. sm4.sm4_setkey_enc(ctx, keyBytes);
  703. byte[] encrypted = sm4.sm4_crypt_ecb(ctx, Encoding.Default.GetBytes(plainText));
  704. string cipherText = Encoding.Default.GetString(Hex.Encode(encrypted));
  705. return cipherText;
  706. }
  707. public string Decrypt_ECB(string cipherText,string key)
  708. {
  709. this.secretKey = key;
  710. return Decrypt_ECB(cipherText);
  711. }
  712. public string Decrypt_ECB(string cipherText)
  713. {
  714. SM4_Context ctx = new SM4_Context();
  715. ctx.isPadding = true;
  716. ctx.mode = SM4.SM4_DECRYPT;
  717. byte[] keyBytes;
  718. if (hexstring)
  719. {
  720. keyBytes = Hex.Decode(secretKey);
  721. }
  722. else
  723. {
  724. keyBytes = Encoding.Default.GetBytes(secretKey);
  725. }
  726. SM4 sm4 = new SM4();
  727. sm4.sm4_setkey_dec(ctx, keyBytes);
  728. byte[] decrypted = sm4.sm4_crypt_ecb(ctx, Hex.Decode(cipherText));
  729. return Encoding.Default.GetString(decrypted);
  730. }
  731. public string Encrypt_CBC(string plainText)
  732. {
  733. SM4_Context ctx = new SM4_Context();
  734. ctx.isPadding = true;
  735. ctx.mode = SM4.SM4_ENCRYPT;
  736. byte[] keyBytes;
  737. byte[] ivBytes;
  738. if (hexstring)
  739. {
  740. keyBytes = Hex.Decode(secretKey);
  741. ivBytes = Hex.Decode(iv);
  742. }
  743. else
  744. {
  745. keyBytes = Encoding.Default.GetBytes(secretKey);
  746. ivBytes = Encoding.Default.GetBytes(iv);
  747. }
  748. SM4 sm4 = new SM4();
  749. sm4.sm4_setkey_enc(ctx, keyBytes);
  750. byte[] encrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Encoding.Default.GetBytes(plainText));
  751. string cipherText = Encoding.Default.GetString(Hex.Encode(encrypted));
  752. return cipherText;
  753. }
  754. public string Decrypt_CBC(string cipherText)
  755. {
  756. SM4_Context ctx = new SM4_Context();
  757. ctx.isPadding = true;
  758. ctx.mode = SM4.SM4_DECRYPT;
  759. byte[] keyBytes;
  760. byte[] ivBytes;
  761. if (hexstring)
  762. {
  763. keyBytes = Hex.Decode(secretKey);
  764. ivBytes = Hex.Decode(iv);
  765. }
  766. else
  767. {
  768. keyBytes = Encoding.Default.GetBytes(secretKey);
  769. ivBytes = Encoding.Default.GetBytes(iv);
  770. }
  771. SM4 sm4 = new SM4();
  772. sm4.sm4_setkey_dec(ctx, keyBytes);
  773. byte[] decrypted = sm4.sm4_crypt_cbc(ctx, ivBytes, Hex.Decode(cipherText));
  774. return Encoding.Default.GetString(decrypted);
  775. }
  776. }
  777. }