Encrypt.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Security.Cryptography;
  7. using System.Windows.Forms;
  8. using System.Runtime.InteropServices;
  9. using Org.BouncyCastle.Crypto;
  10. using Org.BouncyCastle.Crypto.Macs;
  11. using Org.BouncyCastle.Crypto.Parameters;
  12. using Org.BouncyCastle.Utilities.Encoders;
  13. namespace PTMedicalInsurance.Common
  14. {
  15. class Encrypt
  16. {
  17. public static string ToBase64hmac(string strText, string strKey)
  18. {
  19. HMACSHA1 myHMACSHA1 = new HMACSHA1(Encoding.UTF8.GetBytes(strKey));
  20. byte[] byteText = myHMACSHA1.ComputeHash(Encoding.UTF8.GetBytes(strText));
  21. return System.Convert.ToBase64String(byteText);
  22. }
  23. public static string HMACSHA1Text(string EncryptText, string EncryptKey)
  24. {
  25. //HMACSHA1加密
  26. string message;
  27. string key;
  28. message = EncryptText;
  29. key = EncryptKey;
  30. System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
  31. byte[] keyByte = encoding.GetBytes(key);
  32. HMACSHA1 hmacsha1 = new HMACSHA1(keyByte);
  33. byte[] messageBytes = encoding.GetBytes(message);
  34. byte[] hashmessage = hmacsha1.ComputeHash(messageBytes);
  35. //return ByteToString(hashmessage);
  36. return Convert.ToBase64String(hashmessage);
  37. }
  38. public static string HMACSHA1Text2(string EncryptText, string EncryptKey)
  39. {
  40. //HMACSHA1加密
  41. HMACSHA1 hmacsha1 = new HMACSHA1();
  42. hmacsha1.Key = System.Text.Encoding.UTF8.GetBytes(EncryptKey);
  43. byte[] dataBuffer = System.Text.Encoding.UTF8.GetBytes(EncryptText);
  44. byte[] hashBytes = hmacsha1.ComputeHash(dataBuffer);
  45. return Convert.ToBase64String(hashBytes);
  46. }
  47. public static string SHA256(string str)
  48. {
  49. //如果str有中文,不同Encoding的sha是不同的!!
  50. byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
  51. SHA256Managed Sha256 = new SHA256Managed();
  52. byte[] by = Sha256.ComputeHash(SHA256Data);
  53. //return BitConverter.ToString(by).Replace("-", "").ToLower(); //64
  54. return Convert.ToBase64String(by); //44
  55. }
  56. public static Byte[] SHA256Encrypt(string StrIn)
  57. {
  58. var sha256 = new SHA256Managed();
  59. var Asc = new ASCIIEncoding();
  60. var tmpByte = Asc.GetBytes(StrIn);
  61. //var tmpByte = Encoding.UTF8.GetBytes(StrIn);
  62. var EncryptBytes = sha256.ComputeHash(tmpByte);
  63. sha256.Clear();
  64. return EncryptBytes;
  65. }
  66. public static string GetMD5(string myString)
  67. {
  68. MD5 md5 = new MD5CryptoServiceProvider();
  69. byte[] fromData = System.Text.Encoding.UTF8.GetBytes(myString);
  70. byte[] targetData = md5.ComputeHash(fromData);
  71. string byte2String = null;
  72. for (int i = 0; i < targetData.Length; i++)
  73. {
  74. byte2String += targetData[i].ToString("X2");
  75. }
  76. return byte2String;
  77. }
  78. }
  79. class HaErBinEncrypt
  80. {
  81. [DllImport("HaErBinEncrypt.dll", CharSet = CharSet.Ansi, EntryPoint = "Signature", CallingConvention = CallingConvention.StdCall)]
  82. private static extern int Signature(byte[] userid, byte[] sm2key, byte[] sm4key, byte[] plain, byte[] type, ref IntPtr pSignature, ref IntPtr pCipher);
  83. [DllImport("HaErBinEncrypt.dll", CharSet = CharSet.Ansi, EntryPoint = "EncryptBySM4", CallingConvention = CallingConvention.StdCall)]
  84. private static extern IntPtr EncryptBySM4(byte[] sm4key, byte[] plain);
  85. [DllImport("HaErBinEncrypt.dll", CharSet = CharSet.Ansi, EntryPoint = "DecryptBySM4_ECB", CallingConvention = CallingConvention.StdCall)]
  86. private static extern IntPtr DecryptBySM4_ECB(byte[] sm4key, byte[] pCipher);
  87. [DllImport("HaErBinEncrypt.dll", CharSet = CharSet.Ansi, EntryPoint = "EncryptBySM3HASH", CallingConvention = CallingConvention.StdCall)]
  88. private static extern IntPtr EncryptBySM3HASH(byte[] plain);
  89. const string sm2key = "AYvxpsjPGd06aErh6w8uMFKqXwpV6V0pXJYuP4KfD0s=";
  90. const string sm4key = "RNSNupzo1RAizTKU";
  91. public string Signature(string plain, ref string cipher)
  92. {
  93. byte[] bUID = Encoding.UTF8.GetBytes("");
  94. byte[] bSm2Key = Encoding.UTF8.GetBytes(sm2key);
  95. byte[] bSm4Key = Encoding.UTF8.GetBytes(sm4key);
  96. byte[] bPlain = Encoding.UTF8.GetBytes(plain);
  97. byte[] bType = Encoding.UTF8.GetBytes("asn1");
  98. byte[] btSignature = new byte[10240];
  99. try
  100. {
  101. IntPtr pSignatrue = IntPtr.Zero;
  102. IntPtr pCiper = IntPtr.Zero;
  103. int i = Signature(bUID, bSm2Key, bSm4Key, bPlain, bType, ref pSignatrue, ref pCiper);
  104. cipher = System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pCiper);
  105. return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pSignatrue); ;
  106. }
  107. catch (Exception ex)
  108. {
  109. return "签名异常:" + ex.Message;
  110. }
  111. }
  112. public string Encrypt(string plain)
  113. {
  114. byte[] bSm4Key = Encoding.UTF8.GetBytes(sm4key);
  115. byte[] bPlain = Encoding.UTF8.GetBytes(plain);
  116. IntPtr pCipher = IntPtr.Zero;
  117. try
  118. {
  119. pCipher = EncryptBySM4(bSm4Key, bPlain);
  120. return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pCipher);
  121. }
  122. catch (Exception ex)
  123. {
  124. return "解密异常:" + ex.Message;
  125. }
  126. }
  127. public string Decrypt(string cipher)
  128. {
  129. byte[] bSm4Key = Encoding.UTF8.GetBytes(sm4key);
  130. byte[] bCipher = Encoding.UTF8.GetBytes(cipher);
  131. IntPtr pPlain = IntPtr.Zero;
  132. try
  133. {
  134. pPlain = DecryptBySM4_ECB(bSm4Key, bCipher);
  135. return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pPlain);
  136. }
  137. catch (Exception ex)
  138. {
  139. return "解密异常:" + ex.Message;
  140. }
  141. }
  142. public static string EncryptBySM3HASH(string plain)
  143. {
  144. byte[] bPlain = Encoding.UTF8.GetBytes(plain);
  145. IntPtr pCipher = IntPtr.Zero;
  146. try
  147. {
  148. pCipher = EncryptBySM3HASH(bPlain);
  149. return System.Runtime.InteropServices.Marshal.PtrToStringAnsi(pCipher);
  150. }
  151. catch (Exception ex)
  152. {
  153. return "解密异常:" + ex.Message;
  154. }
  155. }
  156. }
  157. #region SM3
  158. /// <summary>
  159. /// General
  160. /// </summary>
  161. public abstract class GeneralDigest : IDigest
  162. {
  163. /// <summary>
  164. /// 内部缓冲区的大小
  165. /// </summary>
  166. private const int ByteLength = 64;
  167. /// <summary>
  168. /// 消息摘要
  169. /// </summary>
  170. private readonly byte[] XBuf;
  171. /// <summary>
  172. /// 待更新的消息摘要的索引
  173. /// </summary>
  174. private int XBufOff;
  175. /// <summary>
  176. /// 待更新的消息摘要的大小
  177. /// </summary>
  178. private long ByteCount;
  179. /// <summary>
  180. /// 构造函数
  181. /// </summary>
  182. internal GeneralDigest()
  183. {
  184. XBuf = new byte[4];
  185. }
  186. /// <summary>
  187. /// 复制构造函数
  188. /// </summary>
  189. /// <param name="t"></param>
  190. internal GeneralDigest(GeneralDigest t)
  191. {
  192. XBuf = new byte[t.XBuf.Length];
  193. Array.Copy(t.XBuf, 0, XBuf, 0, t.XBuf.Length);
  194. XBufOff = t.XBufOff;
  195. ByteCount = t.ByteCount;
  196. }
  197. /// <summary>
  198. /// 用一个字节更新消息摘要。
  199. /// </summary>
  200. /// <param name="input"></param>
  201. public void Update(byte input)
  202. {
  203. XBuf[XBufOff++] = input;
  204. if (XBufOff == XBuf.Length)
  205. {
  206. ProcessWord(XBuf, 0);
  207. XBufOff = 0;
  208. }
  209. ByteCount++;
  210. }
  211. /// <summary>
  212. /// 用字节块更新消息摘要
  213. /// </summary>
  214. /// <param name="input"></param>
  215. /// <param name="inOff"></param>
  216. /// <param name="length"></param>
  217. public void BlockUpdate(byte[] input, int inOff, int length)
  218. {
  219. //更新当前消息摘要
  220. while ((XBufOff != 0) && (length > 0))
  221. {
  222. Update(input[inOff]);
  223. inOff++;
  224. length--;
  225. }
  226. //处理完整的消息摘要
  227. while (length > XBuf.Length)
  228. {
  229. ProcessWord(input, inOff);
  230. inOff += XBuf.Length;
  231. length -= XBuf.Length;
  232. ByteCount += XBuf.Length;
  233. }
  234. //填充剩余的消息摘要
  235. while (length > 0)
  236. {
  237. Update(input[inOff]);
  238. inOff++;
  239. length--;
  240. }
  241. }
  242. /// <summary>
  243. /// 产生最终的摘要值
  244. /// </summary>
  245. public void Finish()
  246. {
  247. long bitLength = (ByteCount << 3);
  248. //添加字节
  249. Update(unchecked((byte)128));
  250. while (XBufOff != 0) Update(unchecked((byte)0));
  251. ProcessLength(bitLength);
  252. ProcessBlock();
  253. }
  254. /// <summary>
  255. /// 重启
  256. /// </summary>
  257. public virtual void Reset()
  258. {
  259. ByteCount = 0;
  260. XBufOff = 0;
  261. Array.Clear(XBuf, 0, XBuf.Length);
  262. }
  263. /// <summary>
  264. /// 摘要应用其压缩功能的内部缓冲区的大小
  265. /// </summary>
  266. /// <returns></returns>
  267. public int GetByteLength()
  268. {
  269. return ByteLength;
  270. }
  271. /// <summary>
  272. /// 处理消息摘要
  273. /// ABCDEFGH 串联
  274. /// </summary>
  275. /// <param name="input"></param>
  276. /// <param name="inOff"></param>
  277. internal abstract void ProcessWord(byte[] input, int inOff);
  278. internal abstract void ProcessLength(long bitLength);
  279. /// <summary>
  280. /// 迭代压缩
  281. /// </summary>
  282. internal abstract void ProcessBlock();
  283. /// <summary>
  284. /// 算法名称
  285. /// </summary>
  286. public abstract string AlgorithmName { get; }
  287. /// <summary>
  288. /// 消息摘要生成的摘要的大小
  289. /// </summary>
  290. /// <returns></returns>
  291. public abstract int GetDigestSize();
  292. /// <summary>
  293. /// 关闭摘要,产生最终的摘要值。doFinal调用使摘要复位。
  294. /// </summary>
  295. /// <param name="output"></param>
  296. /// <param name="outOff"></param>
  297. /// <returns></returns>
  298. public abstract int DoFinal(byte[] output, int outOff);
  299. }
  300. /// <summary>
  301. /// 使用指定的数字执行无符号按位右移
  302. /// </summary>
  303. public class SupportClass
  304. {
  305. /// <summary>
  306. /// 使用指定的数字执行无符号按位右移
  307. /// </summary>
  308. /// <param name="number">要操作的编号</param>
  309. /// <param name="bits">要移位的比特数</param>
  310. /// <returns>移位操作产生的数字</returns>
  311. public static int URShift(int number, int bits)
  312. {
  313. if (number >= 0)
  314. return number >> bits;
  315. else
  316. return (number >> bits) + (2 << ~bits);
  317. }
  318. /// <summary>
  319. /// 使用指定的数字执行无符号按位右移
  320. /// </summary>
  321. /// <param name="number">要操作的编号</param>
  322. /// <param name="bits">要移位的比特数</param>
  323. /// <returns>移位操作产生的数字</returns>
  324. public static int URShift(int number, long bits)
  325. {
  326. return URShift(number, (int)bits);
  327. }
  328. /// <summary>
  329. /// 使用指定的数字执行无符号按位右移
  330. /// </summary>
  331. /// <param name="number">要操作的编号</param>
  332. /// <param name="bits">要移位的比特数</param>
  333. /// <returns>移位操作产生的数字</returns>
  334. public static long URShift(long number, int bits)
  335. {
  336. if (number >= 0)
  337. return number >> bits;
  338. else
  339. return (number >> bits) + (2L << ~bits);
  340. }
  341. /// <summary>
  342. /// 使用指定的数字执行无符号按位右移
  343. /// </summary>
  344. /// <param name="number">要操作的编号</param>
  345. /// <param name="bits">要移位的比特数</param>
  346. /// <returns>移位操作产生的数字</returns>
  347. public static long URShift(long number, long bits)
  348. {
  349. return URShift(number, (int)bits);
  350. }
  351. }
  352. /// <summary>
  353. ///
  354. /// ⊕ 等价于 ^
  355. /// ^ 等价于 &
  356. /// v 等价于 |
  357. /// </summary>
  358. public class SM3Digest : GeneralDigest
  359. {
  360. public override string AlgorithmName
  361. {
  362. get
  363. {
  364. return "SM3";
  365. }
  366. }
  367. /// <summary>
  368. /// 消息摘要生成的摘要的大小
  369. /// </summary>
  370. /// <returns></returns>
  371. public override int GetDigestSize()
  372. {
  373. return DigestLength;
  374. }
  375. /// <summary>
  376. /// SM3算法产生的哈希值大小
  377. /// </summary>
  378. private const int DigestLength = 32;
  379. /// <summary>
  380. /// 初始值IV
  381. /// </summary>
  382. private static readonly int[] IV = new int[] {
  383. 0x7380166f, 0x4914b2b9, 0x172442d7,
  384. unchecked((int)0xda8a0600), unchecked((int)0xa96f30bc), 0x163138aa,
  385. unchecked((int)0xe38dee4d), unchecked((int)0xb0fb0e4e)
  386. };
  387. /// <summary>
  388. /// 备份的字寄存器
  389. /// </summary>
  390. private readonly int[] v = new int[8];
  391. /// <summary>
  392. /// 使用中的字寄存器
  393. /// </summary>
  394. private readonly int[] v_ = new int[8];
  395. private static readonly int[] X0 = new int[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
  396. private readonly int[] X = new int[68];
  397. private int xOff;
  398. /// <summary>
  399. /// 0到15的Tj常量
  400. /// </summary>
  401. private readonly int TOne = 0x79cc4519;
  402. /// <summary>
  403. /// 16到63的Tj常量
  404. /// </summary>
  405. private readonly int TSecond = 0x7a879d8a;
  406. public SM3Digest()
  407. {
  408. Reset();
  409. }
  410. /// <summary>
  411. /// 复制构造函数
  412. /// </summary>
  413. /// <param name="t"></param>
  414. public SM3Digest(SM3Digest t) : base(t)
  415. {
  416. Array.Copy(t.X, 0, X, 0, t.X.Length);
  417. xOff = t.xOff;
  418. Array.Copy(t.v, 0, v, 0, t.v.Length);
  419. }
  420. /// <summary>
  421. /// 将复制的对象状态还原到该对象。
  422. /// 此方法的实现应尝试避免或最小化内存分配以执行重置。
  423. /// </summary>
  424. public override void Reset()
  425. {
  426. base.Reset();
  427. Array.Copy(IV, 0, v, 0, IV.Length);
  428. xOff = 0;
  429. Array.Copy(X0, 0, X, 0, X0.Length);
  430. }
  431. internal override void ProcessBlock()
  432. {
  433. int j;
  434. int[] ww = X;
  435. //64位比特串
  436. int[] ww_ = new int[64];
  437. #region 块消息扩展
  438. //消息扩展16 TO 67
  439. for (j = 16; j < 68; j++)
  440. {
  441. ww[j] = P1(ww[j - 16] ^ ww[j - 9] ^ (Rotate(ww[j - 3], 15))) ^ (Rotate(ww[j - 13], 7)) ^ ww[j - 6];
  442. }
  443. //消息扩展0 TO 63
  444. for (j = 0; j < 64; j++)
  445. {
  446. ww_[j] = ww[j] ^ ww[j + 4];
  447. }
  448. #endregion
  449. #region 压缩函数
  450. int[] vv = v;
  451. int[] vv_ = v_;//A,B,C,D,E,F,G,H为字寄存器
  452. Array.Copy(vv, 0, vv_, 0, IV.Length);
  453. //中间变量SS1,SS2,TT1,TT2
  454. int SS1, SS2, TT1, TT2;
  455. int aaa;
  456. //将消息分组B(i)划分为16个字
  457. for (j = 0; j < 16; j++)
  458. {
  459. aaa = Rotate(vv_[0], 12);
  460. SS1 = aaa + vv_[4] + Rotate(TOne, j);
  461. SS1 = Rotate(SS1, 7);
  462. SS2 = SS1 ^ aaa;
  463. TT1 = FFOne(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[j];
  464. TT2 = GGOne(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[j];
  465. #region 更新各个寄存器
  466. vv_[3] = vv_[2];
  467. vv_[2] = Rotate(vv_[1], 9);
  468. vv_[1] = vv_[0];
  469. vv_[0] = TT1;
  470. vv_[7] = vv_[6];
  471. vv_[6] = Rotate(vv_[5], 19);
  472. vv_[5] = vv_[4];
  473. vv_[4] = P0(TT2);
  474. #endregion
  475. }
  476. for (j = 16; j < 64; j++)
  477. {
  478. aaa = Rotate(vv_[0], 12);
  479. SS1 = aaa + vv_[4] + Rotate(TSecond, j);
  480. SS1 = Rotate(SS1, 7);
  481. SS2 = SS1 ^ aaa;
  482. TT1 = FFSecond(vv_[0], vv_[1], vv_[2]) + vv_[3] + SS2 + ww_[j];
  483. TT2 = GGSecond(vv_[4], vv_[5], vv_[6]) + vv_[7] + SS1 + ww[j];
  484. #region 更新各个寄存器
  485. vv_[3] = vv_[2];
  486. vv_[2] = Rotate(vv_[1], 9);
  487. vv_[1] = vv_[0];
  488. vv_[0] = TT1;
  489. vv_[7] = vv_[6];
  490. vv_[6] = Rotate(vv_[5], 19);
  491. vv_[5] = vv_[4];
  492. vv_[4] = P0(TT2);
  493. #endregion
  494. }
  495. #endregion
  496. //256比特的杂凑值y =vv_(j+1) ABCDEFGH
  497. for (j = 0; j < 8; j++)
  498. {
  499. vv[j] ^= vv_[j];
  500. }
  501. // Reset
  502. xOff = 0;
  503. Array.Copy(X0, 0, X, 0, X0.Length);
  504. }
  505. internal override void ProcessWord(byte[] in_Renamed, int inOff)
  506. {
  507. int n = in_Renamed[inOff] << 24;
  508. n |= (in_Renamed[++inOff] & 0xff) << 16;
  509. n |= (in_Renamed[++inOff] & 0xff) << 8;
  510. n |= (in_Renamed[++inOff] & 0xff);
  511. X[xOff] = n;
  512. if (++xOff == 16)
  513. {
  514. ProcessBlock();
  515. }
  516. }
  517. internal override void ProcessLength(long bitLength)
  518. {
  519. if (xOff > 14)
  520. {
  521. ProcessBlock();
  522. }
  523. X[14] = (int)(SupportClass.URShift(bitLength, 32));
  524. X[15] = (int)(bitLength & unchecked((int)0xffffffff));
  525. }
  526. /// <summary>
  527. /// 写入到大端
  528. /// </summary>
  529. /// <param name="n"></param>
  530. /// <param name="bs"></param>
  531. /// <param name="off"></param>
  532. public static void IntToBigEndian(int n, byte[] bs, int off)
  533. {
  534. bs[off] = (byte)(SupportClass.URShift(n, 24));
  535. bs[++off] = (byte)(SupportClass.URShift(n, 16));
  536. bs[++off] = (byte)(SupportClass.URShift(n, 8));
  537. bs[++off] = (byte)(n);
  538. }
  539. /// <summary>
  540. /// 关闭摘要,产生最终的摘要值。doFinal调用使摘要复位。
  541. /// </summary>
  542. /// <param name="out_Renamed"></param>
  543. /// <param name="outOff"></param>
  544. /// <returns></returns>
  545. public override int DoFinal(byte[] out_Renamed, int outOff)
  546. {
  547. Finish();
  548. for (int i = 0; i < 8; i++)
  549. {
  550. IntToBigEndian(v[i], out_Renamed, outOff + i * 4);
  551. }
  552. Reset();
  553. return DigestLength;
  554. }
  555. /// <summary>
  556. /// x循环左移n比特运算
  557. /// </summary>
  558. /// <param name="x"></param>
  559. /// <param name="n"></param>
  560. /// <returns></returns>
  561. private static int Rotate(int x, int n)
  562. {
  563. return (x << n) | (SupportClass.URShift(x, (32 - n)));
  564. }
  565. #region 置换函数
  566. /// <summary>
  567. /// 置换函数P0
  568. /// </summary>
  569. /// <param name="x"></param>
  570. /// <returns></returns>
  571. private static int P0(int x)
  572. {
  573. return (x) ^ Rotate(x, 9) ^ Rotate(x, 17);
  574. }
  575. /// <summary>
  576. /// 置换函数P1
  577. /// </summary>
  578. /// <param name="x"></param>
  579. /// <returns></returns>
  580. private static int P1(int x)
  581. {
  582. return (x) ^ Rotate(x, 15) ^ Rotate(x, 23);
  583. }
  584. #endregion
  585. #region 布尔函数
  586. /// <summary>
  587. /// 0到15的布尔函数FF (X⊕^Y⊕Z)
  588. /// </summary>
  589. /// <param name="X"></param>
  590. /// <param name="Y"></param>
  591. /// <param name="Z"></param>
  592. /// <returns></returns>
  593. private static int FFOne(int X, int Y, int Z)
  594. {
  595. return (X ^ Y ^ Z);
  596. }
  597. /// <summary>
  598. /// 16到63的布尔函数FF
  599. /// </summary>
  600. /// <param name="X"></param>
  601. /// <param name="Y"></param>
  602. /// <param name="Z"></param>
  603. /// <returns></returns>
  604. private static int FFSecond(int X, int Y, int Z)
  605. {
  606. return ((X & Y) | (X & Z) | (Y & Z));
  607. }
  608. /// <summary>
  609. /// 0到15的布尔函数GG
  610. /// </summary>
  611. /// <param name="X"></param>
  612. /// <param name="Y"></param>
  613. /// <param name="Z"></param>
  614. /// <returns></returns>
  615. private static int GGOne(int X, int Y, int Z)
  616. {
  617. return (X ^ Y ^ Z);
  618. }
  619. /// <summary>
  620. /// 16到63的布尔函数GG
  621. /// </summary>
  622. /// <param name="X"></param>
  623. /// <param name="Y"></param>
  624. /// <param name="Z"></param>
  625. /// <returns></returns>
  626. private static int GGSecond(int X, int Y, int Z)
  627. {
  628. return ((X & Y) | (~X & Z));
  629. }
  630. #endregion
  631. }
  632. /// <summary>
  633. /// Sm3算法(10进制的ASCII)
  634. /// 在SHA-256基础上改进实现的一种算法
  635. /// 对标国际MD5算法和SHA算法
  636. /// </summary>
  637. public static class Sm3Crypto
  638. {
  639. /// <summary>
  640. /// sm3加密(使用自定义密钥)
  641. /// </summary>
  642. /// <param name="data"></param>
  643. /// <returns></returns>
  644. public static byte[] ToSM3byte(string data, string key)
  645. {
  646. byte[] msg1 = Encoding.Default.GetBytes(data);
  647. byte[] key1 = Encoding.Default.GetBytes(key);
  648. KeyParameter keyParameter = new KeyParameter(key1);
  649. SM3Digest sm3 = new SM3Digest();
  650. HMac mac = new HMac(sm3);//带密钥的杂凑算法
  651. mac.Init(keyParameter);
  652. mac.BlockUpdate(msg1, 0, msg1.Length);
  653. byte[] result = new byte[mac.GetMacSize()];
  654. mac.DoFinal(result, 0);
  655. return Hex.Encode(result);
  656. }
  657. /// <summary>
  658. /// sm3加密
  659. /// </summary>
  660. /// <param name="data"></param>
  661. /// <returns></returns>
  662. public static byte[] ToSM3byte(this string data)
  663. {
  664. var msg = ToHexByte(data);//把字符串转成16进制的ASCII码
  665. SM3Digest sm3 = new SM3Digest();
  666. sm3.BlockUpdate(msg, 0, msg.Length);
  667. byte[] md = new byte[sm3.GetDigestSize()];//SM3算法产生的哈希值大小
  668. sm3.DoFinal(md, 0);
  669. return Hex.Encode(md);
  670. }
  671. /// <summary>
  672. /// 字符串转16进制字节数组
  673. /// </summary>
  674. /// <param name="data"></param>
  675. /// <returns></returns>
  676. public static byte[] ToHexByte(string data)
  677. {
  678. byte[] msg1 = Encoding.Default.GetBytes(data);
  679. string hexString = BytesToHexString(msg1);
  680. byte[] returnBytes = new byte[hexString.Length / 2];
  681. for (int i = 0; i < returnBytes.Length; i++)
  682. returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 10);
  683. return returnBytes;
  684. }
  685. /// <summary>
  686. /// byte[]数组转16进制字符串
  687. /// </summary>
  688. /// <param name="input">byte[]数组</param>
  689. /// <returns>16进制字符串</returns>
  690. public static string BytesToHexString(byte[] input)
  691. {
  692. StringBuilder hexString = new StringBuilder(64);
  693. for (int i = 0; i < input.Length; i++)
  694. {
  695. hexString.Append(String.Format("{0:X2}", input[i]));
  696. }
  697. return hexString.ToString();
  698. }
  699. }
  700. #endregion
  701. #region JAVASHA256
  702. public static class JAVASHA256
  703. {
  704. /*** 获取随机数 */
  705. public static String getRandomString(int length)
  706. {
  707. String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  708. Random random = new Random();
  709. StringBuilder sb = new StringBuilder();
  710. for (int i = 0; i < length; ++i)
  711. {
  712. int number = random.Next(62);
  713. sb.Append(str.Substring(number, 1));
  714. }
  715. return sb.ToString();
  716. }
  717. /*** 获取当前时间戳 */
  718. //private static long getCurrentUnixSeconds()
  719. //{
  720. // ZoneOffset zoneOffset = ZoneOffset.ofHours(8);
  721. // LocalDateTime localDateTime = LocalDateTime.now();
  722. // return localDateTime.toEpochSecond(zoneOffset);
  723. //}
  724. public static String byte2Hex(byte[] bytes)
  725. {
  726. StringBuilder stringBuffer = new StringBuilder();
  727. String temp = null;
  728. for (int i = 0; i < bytes.Length; ++i)
  729. {
  730. temp = bytes[i].ToString("X2");
  731. if (temp.Length == 1)
  732. {
  733. stringBuffer.Append("0");
  734. }
  735. stringBuffer.Append(temp);
  736. }
  737. return stringBuffer.ToString();
  738. }
  739. }
  740. #endregion
  741. }