Security.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. using System;
  2. using System.IO;
  3. using System.Security.Cryptography;
  4. using System.Text;
  5. namespace CommonTool
  6. {
  7. public class SysSecurity
  8. {
  9. private static string _Key = "HaiTingA";
  10. public static string Get8Key(string pcKey)
  11. {
  12. #pragma warning disable 618
  13. return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(pcKey, "md5")?.Substring(0, 8);
  14. #pragma warning restore 618
  15. }
  16. public static string Encrypt(string pToEncrypt)
  17. {
  18. return Encrypt(pToEncrypt, _Key);
  19. }
  20. //加密方法
  21. /// <summary>
  22. /// 加密一个字符串
  23. /// </summary>
  24. /// <param name="pToEncrypt">要加密的字符串</param>
  25. /// <param name="sKey">密约</param>
  26. /// <returns></returns>
  27. public static string Encrypt(string pToEncrypt, string sKey)
  28. {
  29. if (string.IsNullOrEmpty(pToEncrypt))
  30. return "";
  31. try
  32. {
  33. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  34. byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
  35. des.Key = Encoding.ASCII.GetBytes(sKey);
  36. des.IV = Encoding.ASCII.GetBytes(sKey);
  37. MemoryStream ms = new MemoryStream();
  38. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  39. cs.Write(inputByteArray, 0, inputByteArray.Length);
  40. cs.FlushFinalBlock();
  41. StringBuilder ret = new StringBuilder();
  42. foreach (byte b in ms.ToArray())
  43. {
  44. ret.AppendFormat("{0:X2}", b);
  45. }
  46. return ret.ToString();
  47. }
  48. catch (Exception e)
  49. {
  50. throw e;
  51. }
  52. }
  53. public static string Decrypt(string pToDecrypt)
  54. {
  55. return Decrypt(pToDecrypt, _Key);
  56. }
  57. //解密方法
  58. /// <summary>
  59. /// 解密一个字符串
  60. /// </summary>
  61. /// <param name="pToDecrypt">要解密的字符串</param>
  62. /// <param name="sKey">解密钥</param>
  63. /// <returns></returns>
  64. public static string Decrypt(string pToDecrypt, string sKey)
  65. {
  66. if (string.IsNullOrEmpty(pToDecrypt))
  67. return "";
  68. try
  69. {
  70. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  71. byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
  72. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  73. {
  74. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  75. inputByteArray[x] = (byte)i;
  76. }
  77. des.Key = Encoding.ASCII.GetBytes(sKey);
  78. des.IV = Encoding.ASCII.GetBytes(sKey);
  79. MemoryStream ms = new MemoryStream();
  80. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  81. cs.Write(inputByteArray, 0, inputByteArray.Length);
  82. cs.FlushFinalBlock();
  83. //StringBuilder ret = new StringBuilder();
  84. return Encoding.Default.GetString(ms.ToArray());
  85. }
  86. catch (Exception e)
  87. {
  88. throw e;
  89. }
  90. }
  91. //private static string _Key = "HaiTingA";
  92. public static string Encrypt4CPlus(string pToEncrypt)
  93. {
  94. return Encrypt4CPlus(pToEncrypt, _Key);
  95. }
  96. public static string Encrypt4CPlus(string pToEncrypt, string sKey)
  97. {
  98. if (pToEncrypt.Length == 0)
  99. return "";
  100. //byte[] Keys = { 0xEF, 0xAB, 0x56, 0x78, 0x90, 0x34, 0xCD, 0x12 };
  101. byte[] keys = { 0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01 };
  102. try
  103. {
  104. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  105. byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
  106. /*des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
  107. des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);*/
  108. des.Key = Encoding.Default.GetBytes(sKey);
  109. des.IV = keys;
  110. //
  111. des.Mode = CipherMode.ECB;
  112. des.Padding = PaddingMode.Zeros;
  113. //
  114. MemoryStream ms = new MemoryStream();
  115. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  116. cs.Write(inputByteArray, 0, inputByteArray.Length);
  117. cs.FlushFinalBlock();
  118. StringBuilder ret = new StringBuilder();
  119. foreach (byte b in ms.ToArray())
  120. {
  121. ret.AppendFormat("{0:X2}", b);
  122. }
  123. return ret.ToString();
  124. }
  125. catch (Exception e)
  126. {
  127. throw e;
  128. }
  129. }
  130. public static string Encrypt3Des(string strString, string strKey, Encoding encoding)
  131. {
  132. TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
  133. MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
  134. des.Key = hashMd5.ComputeHash(encoding.GetBytes(strKey));
  135. des.Mode = CipherMode.ECB;
  136. ICryptoTransform desEncrypt = des.CreateEncryptor();
  137. byte[] buffer = encoding.GetBytes(strString);
  138. return Convert.ToBase64String(desEncrypt.TransformFinalBlock(buffer, 0, buffer.Length));
  139. }
  140. /// <summary>
  141. /// 解密
  142. /// </summary>
  143. /// <param name="strString"></param>
  144. /// <param name="strKey"></param>
  145. /// <returns></returns>
  146. public static string Decrypt3Des(string strString, string strKey)
  147. {
  148. TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
  149. MD5CryptoServiceProvider hashMd5 = new MD5CryptoServiceProvider();
  150. des.Key = hashMd5.ComputeHash(Encoding.ASCII.GetBytes(strKey));
  151. des.Mode = CipherMode.ECB;
  152. ICryptoTransform desDecrypt = des.CreateDecryptor();
  153. string result;
  154. try
  155. {
  156. byte[] buffer = Convert.FromBase64String(strString);
  157. result = Encoding.ASCII.GetString(desDecrypt.TransformFinalBlock(buffer, 0, buffer.Length));
  158. }
  159. catch (Exception e)
  160. {
  161. throw (new Exception("null", e));
  162. }
  163. return result;
  164. }
  165. /// <summary>
  166. /// 解密base64 串
  167. /// </summary>
  168. /// <param name="messages"></param>
  169. /// <returns></returns>
  170. public static string Base64Decode(string messages)
  171. {
  172. if ((messages.Length % 4) != 0)
  173. {
  174. throw new ArgumentException("不是正确的BASE64编码,请检查。", "messages");
  175. }
  176. if (!System.Text.RegularExpressions.Regex.IsMatch(messages, "^[A-Z0-9/+=]*$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
  177. {
  178. throw new ArgumentException("包含不正确的BASE64编码,请检查。", "messages");
  179. }
  180. string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  181. int page = messages.Length / 4;
  182. System.Collections.ArrayList outMessage = new System.Collections.ArrayList(page * 3);
  183. char[] message = messages.ToCharArray();
  184. for (int i = 0; i < page; i++)
  185. {
  186. byte[] instr = new byte[4];
  187. instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
  188. instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
  189. instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
  190. instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
  191. byte[] outstr = new byte[3];
  192. outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
  193. if (instr[2] != 64)
  194. {
  195. outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
  196. }
  197. else
  198. {
  199. outstr[2] = 0;
  200. }
  201. if (instr[3] != 64)
  202. {
  203. outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
  204. }
  205. else
  206. {
  207. outstr[2] = 0;
  208. }
  209. outMessage.Add(outstr[0]);
  210. if (outstr[1] != 0)
  211. outMessage.Add(outstr[1]);
  212. if (outstr[2] != 0)
  213. outMessage.Add(outstr[2]);
  214. }
  215. // ReSharper disable once AssignNullToNotNullAttribute
  216. byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
  217. return Encoding.Default.GetString(outbyte);
  218. }
  219. }
  220. //===================================================
  221. /// <summary>
  222. /// 此处定义的是DES加密,为了便于今后的管理和维护
  223. /// 请不要随便改动密码,或者改变了密码后请一定要
  224. /// 牢记先前的密码,否则将会照成不可预料的损失
  225. /// </summary>
  226. public class DesEncrypt
  227. {
  228. #region "member fields"
  229. private string iv = "HaitingA";//SongHongSongHaitingA
  230. private readonly DES _des;
  231. #endregion "member fields"
  232. /// <summary>
  233. /// 构造函数
  234. /// </summary>
  235. public DesEncrypt()
  236. {
  237. _des = new DESCryptoServiceProvider();
  238. }
  239. #region "propertys"
  240. /// <summary>
  241. /// 设置加密密钥
  242. /// </summary>
  243. public string EncryptKey { get; set; } = "YouYouBB";
  244. /// <summary>
  245. /// 要加密字符的编码模式
  246. /// </summary>
  247. public Encoding EncodingMode { get; set; } = new UnicodeEncoding();
  248. #endregion "propertys"
  249. #region "methods"
  250. /// <summary>
  251. /// 加密字符串并返回加密后的结果
  252. /// </summary>
  253. /// <param name="str"></param>
  254. /// <returns></returns>
  255. public string EncryptString(string str)
  256. {
  257. try
  258. {
  259. byte[] ivb = Encoding.ASCII.GetBytes(iv);
  260. byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey);//得到加密密钥
  261. byte[] toEncrypt = EncodingMode.GetBytes(str);//得到要加密的内容
  262. byte[] encrypted;
  263. ICryptoTransform encryptor = _des.CreateEncryptor(keyb, ivb);
  264. MemoryStream msEncrypt = new MemoryStream();
  265. CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  266. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
  267. csEncrypt.FlushFinalBlock();
  268. encrypted = msEncrypt.ToArray();
  269. csEncrypt.Close();
  270. msEncrypt.Close();
  271. return EncodingMode.GetString(encrypted);
  272. }
  273. catch (Exception e)
  274. {
  275. throw e;
  276. }
  277. }
  278. /// <summary>
  279. /// 加密指定的文件,如果成功返回True,否则false
  280. /// </summary>
  281. /// <param name="filePath">要加密的文件路径</param>
  282. /// <param name="outPath">加密后的文件输出路径</param>
  283. public void EncryptFile(string filePath, string outPath)
  284. {
  285. bool isExist = File.Exists(filePath);
  286. if (isExist)//如果存在
  287. {
  288. byte[] ivb = Encoding.ASCII.GetBytes(iv);
  289. byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey);
  290. //得到要加密文件的字节流
  291. FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  292. StreamReader reader = new StreamReader(fin, EncodingMode);
  293. string dataStr = reader.ReadToEnd();
  294. byte[] toEncrypt = EncodingMode.GetBytes(dataStr);
  295. fin.Close();
  296. FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
  297. ICryptoTransform encryptor = _des.CreateEncryptor(keyb, ivb);
  298. CryptoStream csEncrypt = new CryptoStream(fout, encryptor, CryptoStreamMode.Write);
  299. try
  300. {
  301. //加密得到的文件字节流
  302. csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
  303. csEncrypt.FlushFinalBlock();
  304. }
  305. catch (Exception err)
  306. {
  307. throw new ApplicationException(err.Message);
  308. }
  309. finally
  310. {
  311. try
  312. {
  313. fout.Close();
  314. csEncrypt.Close();
  315. }
  316. catch
  317. {
  318. // ignored
  319. }
  320. }
  321. }
  322. else
  323. {
  324. throw new FileNotFoundException("没有找到指定的文件");
  325. }
  326. }
  327. /// <summary>
  328. /// 文件加密函数的重载版本,如果不指定输出路径,
  329. /// 那么原来的文件将被加密后的文件覆盖
  330. /// </summary>
  331. /// <param name="filePath"></param>
  332. public void EncryptFile(string filePath)
  333. {
  334. EncryptFile(filePath, filePath);
  335. }
  336. /// <summary>
  337. /// 解密给定的字符串
  338. /// </summary>
  339. /// <param name="str">要解密的字符</param>
  340. /// <returns></returns>
  341. public string DecryptString(string str)
  342. {
  343. byte[] ivb = Encoding.ASCII.GetBytes(iv);
  344. byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey);
  345. byte[] toDecrypt = EncodingMode.GetBytes(str);
  346. byte[] deCrypted = new byte[toDecrypt.Length];
  347. ICryptoTransform deCryptor = _des.CreateDecryptor(keyb, ivb);
  348. MemoryStream msDecrypt = new MemoryStream(toDecrypt);
  349. CryptoStream csDecrypt = new CryptoStream(msDecrypt, deCryptor, CryptoStreamMode.Read);
  350. try
  351. {
  352. csDecrypt.Read(deCrypted, 0, deCrypted.Length);
  353. }
  354. catch (Exception err)
  355. {
  356. throw new ApplicationException(err.Message);
  357. }
  358. finally
  359. {
  360. try
  361. {
  362. msDecrypt.Close();
  363. csDecrypt.Close();
  364. }
  365. catch
  366. {
  367. // ignored
  368. }
  369. }
  370. return EncodingMode.GetString(deCrypted);
  371. }
  372. /// <summary>
  373. /// 解密指定的文件
  374. /// </summary>
  375. /// <param name="filePath">要解密的文件路径</param>
  376. /// <param name="outPath">解密后的文件输出路径</param>
  377. public void DecryptFile(string filePath, string outPath)
  378. {
  379. bool isExist = File.Exists(filePath);
  380. if (isExist)//如果存在
  381. {
  382. byte[] ivb = Encoding.ASCII.GetBytes(iv);
  383. byte[] keyb = Encoding.ASCII.GetBytes(EncryptKey);
  384. FileInfo file = new FileInfo(filePath);
  385. byte[] deCrypted = new byte[file.Length];
  386. //得到要解密文件的字节流
  387. FileStream fin = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  388. //解密文件
  389. try
  390. {
  391. ICryptoTransform decryptor = _des.CreateDecryptor(keyb, ivb);
  392. CryptoStream csDecrypt = new CryptoStream(fin, decryptor, CryptoStreamMode.Read);
  393. csDecrypt.Read(deCrypted, 0, deCrypted.Length);
  394. }
  395. catch (Exception err)
  396. {
  397. throw new ApplicationException(err.Message);
  398. }
  399. finally
  400. {
  401. try
  402. {
  403. fin.Close();
  404. }
  405. catch
  406. {
  407. // ignored
  408. }
  409. }
  410. FileStream fout = new FileStream(outPath, FileMode.Create, FileAccess.Write);
  411. fout.Write(deCrypted, 0, deCrypted.Length);
  412. fout.Close();
  413. }
  414. else
  415. {
  416. throw new FileNotFoundException("指定的解密文件没有找到");
  417. }
  418. }
  419. /// <summary>
  420. /// 解密文件的重载版本,如果没有给出解密后文件的输出路径,
  421. /// 则解密后的文件将覆盖先前的文件
  422. /// </summary>
  423. /// <param name="filePath"></param>
  424. public void DecryptFile(string filePath)
  425. {
  426. DecryptFile(filePath, filePath);
  427. }
  428. #endregion "methods"
  429. }
  430. //===============================================================
  431. /// <summary>
  432. /// MD5加密类,注意经MD5加密过的信息是不能转换回原始数据的
  433. /// ,请不要在用户敏感的信息中使用此加密技术,比如用户的密码,
  434. /// 请尽量使用对称加密
  435. /// </summary>
  436. public class Md5Encrypt
  437. {
  438. private readonly MD5 _md5;
  439. public Md5Encrypt()
  440. {
  441. _md5 = new MD5CryptoServiceProvider();
  442. }
  443. /// <summary>
  444. /// 从字符串中获取散列值
  445. /// </summary>
  446. /// <param name="str">要计算散列值的字符串</param>
  447. /// <returns></returns>
  448. public string GetMd5FromString(string str)
  449. {
  450. byte[] toCompute = Encoding.Unicode.GetBytes(str);
  451. byte[] hashed = _md5.ComputeHash(toCompute, 0, toCompute.Length);
  452. return Encoding.ASCII.GetString(hashed);
  453. }
  454. /// <summary>
  455. /// 根据文件来计算散列值
  456. /// </summary>
  457. /// <param name="filePath">要计算散列值的文件路径</param>
  458. /// <returns></returns>
  459. public string GetMd5FromFile(string filePath)
  460. {
  461. bool isExist = File.Exists(filePath);
  462. if (isExist)//如果文件存在
  463. {
  464. FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
  465. StreamReader reader = new StreamReader(stream, Encoding.Unicode);
  466. string str = reader.ReadToEnd();
  467. byte[] toHash = Encoding.Unicode.GetBytes(str);
  468. byte[] hashed = _md5.ComputeHash(toHash, 0, toHash.Length);
  469. stream.Close();
  470. return Encoding.ASCII.GetString(hashed);
  471. }
  472. //文件不存在
  473. throw new FileNotFoundException("指定的文件没有找到");
  474. }
  475. }
  476. //================================================================
  477. /// <summary>
  478. /// 用于数字签名的hash类
  479. /// </summary>
  480. public class MacTripleDesEncrypt
  481. {
  482. private string _key = "ksn168ch";
  483. public MacTripleDesEncrypt()
  484. {
  485. Mact = new MACTripleDES();
  486. }
  487. /// <summary>
  488. /// 获取或设置用于数字签名的密钥
  489. /// </summary>
  490. public string Key
  491. {
  492. get { return _key; }
  493. set
  494. {
  495. int keyLength = value.Length;
  496. int[] keyAllowLengths = { 8, 16, 24 };
  497. bool isRight = false;
  498. foreach (int i in keyAllowLengths)
  499. {
  500. if (keyLength == keyAllowLengths[i])
  501. {
  502. isRight = true;
  503. break;
  504. }
  505. }
  506. if (!isRight)
  507. throw new ApplicationException("用于数字签名的密钥长度必须是8,16,24值之一");
  508. _key = value;
  509. }
  510. }
  511. /// <summary>
  512. /// 获取或设置用于数字签名的用户数据
  513. /// </summary>
  514. public byte[] Data { get; set; }
  515. public MACTripleDES Mact { get; set; }
  516. /// <summary>
  517. /// 得到签名后的hash值
  518. /// </summary>
  519. /// <returns></returns>
  520. public string GetHashValue()
  521. {
  522. if (Data == null)
  523. throw new Exception("没有设置要进行数字签名的用户" +
  524. "数据(property:Data)");
  525. byte[] key = Encoding.ASCII.GetBytes(Key);
  526. Mact.Key = key;
  527. byte[] hashB = Mact.ComputeHash(Mact.ComputeHash(Data));
  528. return Encoding.ASCII.GetString(hashB);
  529. }
  530. }
  531. }