SysSecurity.cs 22 KB

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