1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Web;
  8.  
  9. namespace WebDemo.Until
  10. {
  11.  
  12. public class EncryptHelper
  13. {
  14. #region DES对称加密解密
  15.  
  16. /// <summary> 加密字符串
  17. /// </summary>
  18. /// <param name="strText">需被加密的字符串</param>
  19. /// <param name="strEncrKey">密钥</param>
  20. /// <returns></returns>
  21. public static string DesEncrypt(string strText, string strEncrKey)
  22. {
  23. try
  24. {
  25. byte[] byKey = null;
  26. byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  27.  
  28. byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(, ));
  29. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  30. byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
  31. MemoryStream ms = new MemoryStream();
  32. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
  33. cs.Write(inputByteArray, , inputByteArray.Length);
  34. cs.FlushFinalBlock();
  35. return Convert.ToBase64String(ms.ToArray());
  36. }
  37. catch
  38. {
  39. return "";
  40. }
  41. }
  42.  
  43. /// <summary> 解密字符串
  44. /// </summary>
  45. /// <param name="strText">需被解密的字符串</param>
  46. /// <param name="sDecrKey">密钥</param>
  47. /// <returns></returns>
  48. public static string DesDecrypt(string strText, string sDecrKey)
  49. {
  50. try
  51. {
  52. byte[] byKey = null;
  53. byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  54. byte[] inputByteArray = new Byte[strText.Length];
  55.  
  56. byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(, ));
  57. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  58. inputByteArray = Convert.FromBase64String(strText);
  59. MemoryStream ms = new MemoryStream();
  60. CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
  61. cs.Write(inputByteArray, , inputByteArray.Length);
  62. cs.FlushFinalBlock();
  63. Encoding encoding = new UTF8Encoding();
  64. return encoding.GetString(ms.ToArray());
  65. }
  66. catch
  67. {
  68. return null;
  69. }
  70. }
  71.  
  72. /// <summary> 加密文件
  73. ///
  74. /// </summary>
  75. /// <param name="m_InFilePath">原路径</param>
  76. /// <param name="m_OutFilePath">加密后的文件路径</param>
  77. /// <param name="strEncrKey">密钥</param>
  78. public static void DesEncryptFile(string m_InFilePath, string m_OutFilePath, string strEncrKey)
  79. {
  80. try
  81. {
  82. byte[] byKey = null;
  83. byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  84.  
  85. byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(, ));
  86. FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
  87. FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  88. fout.SetLength();
  89. //Create variables to help with read and write.
  90. byte[] bin = new byte[]; //This is intermediate storage for the encryption.
  91. long rdlen = ; //This is the total number of bytes written.
  92. long totlen = fin.Length; //This is the total length of the input file.
  93. int len; //This is the number of bytes to be written at a time.
  94.  
  95. DES des = new DESCryptoServiceProvider();
  96. CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
  97.  
  98. //Read from the input file, then encrypt and write to the output file.
  99. while (rdlen < totlen)
  100. {
  101. len = fin.Read(bin, , );
  102. encStream.Write(bin, , len);
  103. rdlen = rdlen + len;
  104. }
  105. encStream.Close();
  106. fout.Close();
  107. fin.Close();
  108. }
  109. catch
  110. {
  111. }
  112.  
  113. }
  114.  
  115. /// <summary> 解密文件
  116. ///
  117. /// </summary>
  118. /// <param name="m_InFilePath">被解密路径</param>
  119. /// <param name="m_OutFilePath">解密后的路径</param>
  120. /// <param name="sDecrKey">密钥</param>
  121. public static void DesDecryptFile(string m_InFilePath, string m_OutFilePath, string sDecrKey)
  122. {
  123. try
  124. {
  125. byte[] byKey = null;
  126. byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  127.  
  128. byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(, ));
  129. FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
  130. FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  131. fout.SetLength();
  132. //Create variables to help with read and write.
  133. byte[] bin = new byte[]; //This is intermediate storage for the encryption.
  134. long rdlen = ; //This is the total number of bytes written.
  135. long totlen = fin.Length; //This is the total length of the input file.
  136. int len; //This is the number of bytes to be written at a time.
  137.  
  138. DES des = new DESCryptoServiceProvider();
  139. CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
  140.  
  141. //Read from the input file, then encrypt and write to the output file.
  142. while (rdlen < totlen)
  143. {
  144. len = fin.Read(bin, , );
  145. encStream.Write(bin, , len);
  146. rdlen = rdlen + len;
  147. }
  148. encStream.Close();
  149. fout.Close();
  150. fin.Close();
  151. }
  152. catch
  153. {
  154. }
  155. }
  156. #endregion
  157.  
  158. #region 3DES对称加密解密
  159. /// <summary>
  160. ///3DES加密
  161. /// </summary>
  162. /// <param name="originalValue">加密数据</param>
  163. /// <param name="key">24位字符的密钥字符串</param>
  164. /// <param name="IV">8位字符的初始化向量字符串</param>
  165. /// <returns></returns>
  166. public static string DESEncrypt(string originalValue, string key, string IV)
  167. {
  168. SymmetricAlgorithm sa = new TripleDESCryptoServiceProvider();
  169. sa.Mode = CipherMode.CBC;
  170. sa.Padding = PaddingMode.PKCS7;
  171. sa.Key = Encoding.UTF8.GetBytes(key);
  172. sa.IV = Encoding.UTF8.GetBytes(IV);
  173. ICryptoTransform ct = sa.CreateEncryptor();
  174. byte[] byt = Encoding.UTF8.GetBytes(originalValue);
  175. MemoryStream ms = new MemoryStream();
  176. CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
  177. cs.Write(byt, , byt.Length);
  178. cs.FlushFinalBlock();
  179. cs.Close();
  180. return Convert.ToBase64String(ms.ToArray());
  181. }
  182. /// <summary>
  183. /// 3DES解密
  184. /// </summary>
  185. /// <param name="data">解密数据</param>
  186. /// <param name="key">24位字符的密钥字符串(需要和加密时相同)</param>
  187. /// <param name="iv">8位字符的初始化向量字符串(需要和加密时相同)</param>
  188. /// <returns></returns>
  189. public static string DESDecrypst(string data, string key, string IV)
  190. {
  191. SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
  192. mCSP.Mode = CipherMode.CBC;
  193. mCSP.Padding = PaddingMode.PKCS7;
  194. mCSP.Key = Encoding.UTF8.GetBytes(key);
  195. mCSP.IV = Encoding.UTF8.GetBytes(IV);
  196. ICryptoTransform ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);
  197. byte[] byt = Convert.FromBase64String(data);
  198. MemoryStream ms = new MemoryStream();
  199. CryptoStream cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
  200. cs.Write(byt, , byt.Length);
  201. cs.FlushFinalBlock();
  202. cs.Close();
  203. return Encoding.UTF8.GetString(ms.ToArray());
  204. }
  205. #endregion
  206.  
  207. #region AES RijndaelManaged加密解密
  208.  
  209. private static readonly string Default_AES_Key = "@#kim123";
  210. private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
  211. 0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
  212. public static string AES_Encrypt(string encryptString)
  213. {
  214. return AES_Encrypt(encryptString, Default_AES_Key);
  215. }
  216.  
  217. public static string AES_Decrypt(string decryptString)
  218. {
  219. return AES_Decrypt(decryptString, Default_AES_Key);
  220. }
  221.  
  222. #region AES(CBC)有向量(IV)
  223. /// <summary>对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
  224. ///
  225. /// </summary>
  226. /// <param name="encryptString">待加密字符串</param>
  227. /// <param name="encryptKey">加密密钥,须半角字符</param>
  228. /// <returns>加密结果字符串</returns>
  229. public static string AES_Encrypt(string encryptString, string encryptKey)
  230. {
  231. encryptKey = GetSubString(encryptKey, , "");
  232. encryptKey = encryptKey.PadRight(, ' ');
  233.  
  234. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  235. rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
  236. rijndaelProvider.IV = Keys;
  237. ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
  238.  
  239. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  240. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, , inputData.Length);
  241.  
  242. return Convert.ToBase64String(encryptedData);
  243. }
  244.  
  245. /// <summary> 对称加密算法AES RijndaelManaged解密字符串
  246. ///
  247. /// </summary>
  248. /// <param name="decryptString">待解密的字符串</param>
  249. /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
  250. /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
  251. public static string AES_Decrypt(string decryptString, string decryptKey)
  252. {
  253. try
  254. {
  255. decryptKey = GetSubString(decryptKey, , "");
  256. decryptKey = decryptKey.PadRight(, ' ');
  257.  
  258. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  259. rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
  260. rijndaelProvider.IV = Keys;
  261. ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
  262.  
  263. byte[] inputData = Convert.FromBase64String(decryptString);
  264. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, , inputData.Length);
  265.  
  266. return Encoding.UTF8.GetString(decryptedData);
  267. }
  268. catch
  269. {
  270. return string.Empty;
  271. }
  272. }
  273. #endregion
  274.  
  275. #region AES(ECB)无向量(IV)
  276. /// <summary>
  277. /// AES加密(无向量)
  278. /// </summary>
  279. /// <param name="plainBytes">被加密的明文</param>
  280. /// <param name="key">密钥 32 </param>
  281. /// <returns>密文</returns>
  282. public static string AESEncryptECB(string encryptString, string encryptKey)
  283. {
  284. try
  285. {
  286. encryptKey = GetSubString(encryptKey, , "");
  287. encryptKey = encryptKey.PadRight(, ' ');
  288.  
  289. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  290. rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(, ));
  291. rijndaelProvider.Mode = CipherMode.ECB;
  292. rijndaelProvider.Padding = PaddingMode.PKCS7;
  293. ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
  294. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  295. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, , inputData.Length);
  296. return Convert.ToBase64String(encryptedData);
  297. }
  298. catch (Exception ex)
  299. {
  300. return ex.Message;
  301. }
  302. }
  303.  
  304. /// <summary>
  305. /// AES解密(无向量)
  306. /// </summary>
  307. /// <param name="decryptString">被加密的明文</param>
  308. /// <param name="decryptKey">密钥</param>
  309. /// <returns>明文</returns>
  310. public static string AESDecryptECB(string decryptString, string decryptKey)
  311. {
  312. try
  313. {
  314. decryptKey = GetSubString(decryptKey, , "");
  315. decryptKey = decryptKey.PadRight(, ' ');
  316.  
  317. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  318. rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey.Substring(, ));
  319. rijndaelProvider.Mode = CipherMode.ECB;
  320. rijndaelProvider.Padding = PaddingMode.PKCS7;
  321. ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
  322. byte[] inputData = Convert.FromBase64String(decryptString);
  323. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, , inputData.Length);
  324. return Encoding.UTF8.GetString(decryptedData);
  325. }
  326. catch (Exception ex)
  327. {
  328. return ex.Message;
  329. }
  330. }
  331. #endregion
  332.  
  333. /// <summary>
  334. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  335. /// </summary>
  336. /// <param name="sourceString">源字符串</param>
  337. /// <param name="length">所取字符串字节长度</param>
  338. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  339. /// <returns>某字符串的一部分</returns>
  340. private static string GetSubString(string sourceString, int length, string tailString)
  341. {
  342. return GetSubString(sourceString, , length, tailString);
  343. }
  344.  
  345. /// <summary>
  346. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  347. /// </summary>
  348. /// <param name="sourceString">源字符串</param>
  349. /// <param name="startIndex">索引位置,以0开始</param>
  350. /// <param name="length">所取字符串字节长度</param>
  351. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  352. /// <returns>某字符串的一部分</returns>
  353. private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
  354. {
  355. string myResult = sourceString;
  356.  
  357. //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
  358. if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") ||
  359. System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
  360. {
  361. //当截取的起始位置超出字段串长度时
  362. if (startIndex >= sourceString.Length)
  363. {
  364. return string.Empty;
  365. }
  366. else
  367. {
  368. return sourceString.Substring(startIndex,
  369. ((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
  370. }
  371. }
  372.  
  373. //中文字符,如"中国人民abcd123"
  374. if (length <= )
  375. {
  376. return string.Empty;
  377. }
  378. byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
  379.  
  380. //当字符串长度大于起始位置
  381. if (bytesSource.Length > startIndex)
  382. {
  383. int endIndex = bytesSource.Length;
  384.  
  385. //当要截取的长度在字符串的有效长度范围内
  386. if (bytesSource.Length > (startIndex + length))
  387. {
  388. endIndex = length + startIndex;
  389. }
  390. else
  391. { //当不在有效范围内时,只取到字符串的结尾
  392. length = bytesSource.Length - startIndex;
  393. tailString = "";
  394. }
  395.  
  396. int[] anResultFlag = new int[length];
  397. int nFlag = ;
  398. //字节大于127为双字节字符
  399. for (int i = startIndex; i < endIndex; i++)
  400. {
  401. if (bytesSource[i] > )
  402. {
  403. nFlag++;
  404. if (nFlag == )
  405. {
  406. nFlag = ;
  407. }
  408. }
  409. else
  410. {
  411. nFlag = ;
  412. }
  413. anResultFlag[i] = nFlag;
  414. }
  415. //最后一个字节为双字节字符的一半
  416. if ((bytesSource[endIndex - ] > ) && (anResultFlag[length - ] == ))
  417. {
  418. length = length + ;
  419. }
  420.  
  421. byte[] bsResult = new byte[length];
  422. Array.Copy(bytesSource, startIndex, bsResult, , length);
  423. myResult = Encoding.Default.GetString(bsResult);
  424. myResult = myResult + tailString;
  425.  
  426. return myResult;
  427. }
  428.  
  429. return string.Empty;
  430.  
  431. }
  432.  
  433. /// <summary>
  434. /// 加密文件流
  435. /// </summary>
  436. /// <param name="fs"></param>
  437. /// <returns></returns>
  438. public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey)
  439. {
  440. decryptKey = GetSubString(decryptKey, , "");
  441. decryptKey = decryptKey.PadRight(, ' ');
  442.  
  443. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  444. rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
  445. rijndaelProvider.IV = Keys;
  446.  
  447. ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
  448. CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
  449. return cytptostreamEncr;
  450. }
  451.  
  452. /// <summary>
  453. /// 解密文件流
  454. /// </summary>
  455. /// <param name="fs"></param>
  456. /// <returns></returns>
  457. public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey)
  458. {
  459. decryptKey = GetSubString(decryptKey, , "");
  460. decryptKey = decryptKey.PadRight(, ' ');
  461.  
  462. RijndaelManaged rijndaelProvider = new RijndaelManaged();
  463. rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
  464. rijndaelProvider.IV = Keys;
  465. ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
  466. CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
  467. return cytptostreamDecr;
  468. }
  469.  
  470. /// <summary>
  471. /// 对指定文件加密
  472. /// </summary>
  473. /// <param name="InputFile"></param>
  474. /// <param name="OutputFile"></param>
  475. /// <returns></returns>
  476. public static bool AES_EncryptFile(string InputFile, string OutputFile)
  477. {
  478. try
  479. {
  480. string decryptKey = "www.iqidi.com";
  481.  
  482. FileStream fr = new FileStream(InputFile, FileMode.Open);
  483. FileStream fren = new FileStream(OutputFile, FileMode.Create);
  484. CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
  485. byte[] bytearrayinput = new byte[fr.Length];
  486. fr.Read(bytearrayinput, , bytearrayinput.Length);
  487. Enfr.Write(bytearrayinput, , bytearrayinput.Length);
  488. Enfr.Close();
  489. fr.Close();
  490. fren.Close();
  491. }
  492. catch
  493. {
  494. //文件异常
  495. return false;
  496. }
  497. return true;
  498. }
  499.  
  500. /// <summary>
  501. /// 对指定的文件解压缩
  502. /// </summary>
  503. /// <param name="InputFile"></param>
  504. /// <param name="OutputFile"></param>
  505. /// <returns></returns>
  506. public static bool AES_DecryptFile(string InputFile, string OutputFile)
  507. {
  508. try
  509. {
  510. string decryptKey = "www.iqidi.com";
  511. FileStream fr = new FileStream(InputFile, FileMode.Open);
  512. FileStream frde = new FileStream(OutputFile, FileMode.Create);
  513. CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
  514. byte[] bytearrayoutput = new byte[];
  515. int m_count = ;
  516.  
  517. do
  518. {
  519. m_count = Defr.Read(bytearrayoutput, , bytearrayoutput.Length);
  520. frde.Write(bytearrayoutput, , m_count);
  521. if (m_count < bytearrayoutput.Length)
  522. break;
  523. } while (true);
  524.  
  525. Defr.Close();
  526. fr.Close();
  527. frde.Close();
  528. }
  529. catch
  530. {
  531. //文件异常
  532. return false;
  533. }
  534. return true;
  535. }
  536.  
  537. #endregion
  538.  
  539. #region RSA加密 解密
  540.  
  541. /// <summary>RSA加密
  542. ///
  543. /// </summary>
  544. /// <param name="plaintext">明文</param>
  545. /// <param name="publicKey">公钥</param>
  546. /// <returns>密文字符串</returns>
  547. public static string EncryptByRSA(string plaintext, string publicKey)
  548. {
  549. try
  550. {
  551. UnicodeEncoding ByteConverter = new UnicodeEncoding();
  552. byte[] dataToEncrypt = ByteConverter.GetBytes(plaintext);
  553. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
  554. {
  555. RSA.FromXmlString(publicKey);
  556. byte[] encryptedData = RSA.Encrypt(dataToEncrypt, false);
  557. return Convert.ToBase64String(encryptedData);
  558. }
  559. }
  560. catch (Exception)
  561. {
  562. return null;
  563. }
  564.  
  565. }
  566.  
  567. /// <summary> RSA解密
  568. ///
  569. /// </summary>
  570. /// <param name="ciphertext">密文</param>
  571. /// <param name="privateKey">私钥</param>
  572. /// <returns>明文字符串</returns>
  573. public static string DecryptByRSA(string ciphertext, string privateKey)
  574. {
  575. try
  576. {
  577. UnicodeEncoding byteConverter = new UnicodeEncoding();
  578. using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
  579. {
  580. RSA.FromXmlString(privateKey);
  581. byte[] encryptedData = Convert.FromBase64String(ciphertext);
  582. byte[] decryptedData = RSA.Decrypt(encryptedData, false);
  583. return byteConverter.GetString(decryptedData);
  584. }
  585. }
  586. catch (Exception)
  587. {
  588. return null;
  589. }
  590.  
  591. }
  592.  
  593. /// <summary>生成RSA加密 解密的 密钥
  594. /// 生成的key就是 方法EncryptByRSA与DecryptByRSA用的key了
  595. /// </summary>
  596. /// <param name="path">要生成的密钥文件的路径(文件夹)</param>
  597. public static void getRSAKey(string path)
  598. {
  599. RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
  600. string datetimestr = System.DateTime.Now.ToString("yyyyMMddHHmmss");
  601. using (StreamWriter writer = new StreamWriter("RSA解密_PrivateKey_" + datetimestr + ".xml")) //这个文件要保密...
  602. {
  603. writer.WriteLine(rsa.ToXmlString(true));
  604. }
  605. using (StreamWriter writer = new StreamWriter("RSA加密_PublicKey_" + datetimestr + ".xml"))
  606. {
  607. writer.WriteLine(rsa.ToXmlString(false));
  608. }
  609. }
  610. #endregion
  611.  
  612. #region Base64加密解密
  613.  
  614. /// <summary>
  615. /// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
  616. /// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
  617. /// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
  618. /// 系統中而不同。
  619. /// Base64加密
  620. /// </summary>
  621. /// <param name="str"></param>
  622. /// <returns></returns>
  623. public static string Base64Encrypt(string str)
  624. {
  625. byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
  626. return Convert.ToBase64String(encbuff);
  627. }
  628.  
  629. /// <summary>
  630. /// Base64解密
  631. /// </summary>
  632. /// <param name="str"></param>
  633. /// <returns></returns>
  634. public static string Base64Decrypt(string str)
  635. {
  636. byte[] decbuff = Convert.FromBase64String(str);
  637. return System.Text.Encoding.UTF8.GetString(decbuff);
  638. }
  639. #endregion
  640.  
  641. #region MD5
  642. /// <summary>
  643.  
  644. /// 获得32位的MD5加密
  645. /// </summary>
  646. /// <param name="input"></param>
  647. /// <returns></returns>
  648. public static string GetMD5_32(string input)
  649. {
  650. MD5 md5 = MD5.Create();
  651. byte[] data = md5.ComputeHash(Encoding.Default.GetBytes(input));
  652. StringBuilder sb = new StringBuilder();
  653. for (int i = ; i < data.Length; i++)
  654. {
  655. sb.AppendFormat("{0:X2}", data[i]);
  656. }
  657. return sb.ToString();
  658. }
  659.  
  660. /// <summary>
  661. /// 获得16位的MD5加密
  662. /// </summary>
  663. /// <param name="input"></param>
  664. /// <returns></returns>
  665. public static string GetMD5_16(string input)
  666. {
  667. return GetMD5_32(input).Substring(, );
  668. }
  669. /// <summary>
  670. /// 获得8位的MD5加密
  671. /// </summary>
  672. /// <param name="input"></param>
  673. /// <returns></returns>
  674. public static string GetMD5_8(string input)
  675. {
  676. return GetMD5_32(input).Substring(, );
  677. }
  678. /// <summary>
  679. /// 获得4位的MD5加密
  680. /// </summary>
  681. /// <param name="input"></param>
  682. /// <returns></returns>
  683. public static string GetMD5_4(string input)
  684. {
  685. return GetMD5_32(input).Substring(, );
  686. }
  687.  
  688. public static string MD5EncryptHash(String input)
  689. {
  690. MD5 md5 = new MD5CryptoServiceProvider();
  691. //the GetBytes method returns byte array equavalent of a string
  692. byte[] res = md5.ComputeHash(Encoding.Default.GetBytes(input), , input.Length);
  693. char[] temp = new char[res.Length];
  694. //copy to a char array which can be passed to a String constructor
  695. Array.Copy(res, temp, res.Length);
  696. //return the result as a string
  697. return new String(temp);
  698. }
  699. #endregion
  700.  
  701. #region MD5签名验证
  702.  
  703. /// <summary>
  704. /// 对给定文件路径的文件加上标签
  705. /// </summary>
  706. /// <param name="path">要加密的文件的路径</param>
  707. /// <returns>标签的值</returns>
  708. public static bool AddMD5(string path)
  709. {
  710. bool IsNeed = true;
  711.  
  712. if (CheckMD5(path)) //已进行MD5处理
  713. IsNeed = false;
  714.  
  715. try
  716. {
  717. FileStream fsread = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  718. byte[] md5File = new byte[fsread.Length];
  719. fsread.Read(md5File, , (int)fsread.Length); // 将文件流读取到Buffer中
  720. fsread.Close();
  721.  
  722. if (IsNeed)
  723. {
  724. string result = MD5Buffer(md5File, , md5File.Length); // 对Buffer中的字节内容算MD5
  725. byte[] md5 = System.Text.Encoding.ASCII.GetBytes(result); // 将字符串转换成字节数组以便写人到文件中
  726. FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  727. fsWrite.Write(md5File, , md5File.Length); // 将文件,MD5值 重新写入到文件中。
  728. fsWrite.Write(md5, , md5.Length);
  729. fsWrite.Close();
  730. }
  731. else
  732. {
  733. FileStream fsWrite = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);
  734. fsWrite.Write(md5File, , md5File.Length);
  735. fsWrite.Close();
  736. }
  737. }
  738. catch
  739. {
  740. return false;
  741. }
  742.  
  743. return true;
  744. }
  745.  
  746. /// <summary>
  747. /// 对给定路径的文件进行验证
  748. /// </summary>
  749. /// <param name="path"></param>
  750. /// <returns>是否加了标签或是否标签值与内容值一致</returns>
  751. public static bool CheckMD5(string path)
  752. {
  753. try
  754. {
  755. FileStream get_file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read);
  756. byte[] md5File = new byte[get_file.Length]; // 读入文件
  757. get_file.Read(md5File, , (int)get_file.Length);
  758. get_file.Close();
  759.  
  760. string result = MD5Buffer(md5File, , md5File.Length - ); // 对文件除最后32位以外的字节计算MD5,这个32是因为标签位为32位。
  761. string md5 = System.Text.Encoding.ASCII.GetString(md5File, md5File.Length - , ); //读取文件最后32位,其中保存的就是MD5值
  762. return result == md5;
  763. }
  764. catch
  765. {
  766. return false;
  767. }
  768. }
  769.  
  770. /// <summary>
  771. /// 计算文件的MD5值
  772. /// </summary>
  773. /// <param name="MD5File">MD5签名文件字符数组</param>
  774. /// <param name="index">计算起始位置</param>
  775. /// <param name="count">计算终止位置</param>
  776. /// <returns>计算结果</returns>
  777. private static string MD5Buffer(byte[] MD5File, int index, int count)
  778. {
  779. System.Security.Cryptography.MD5CryptoServiceProvider get_md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  780. byte[] hash_byte = get_md5.ComputeHash(MD5File, index, count);
  781. string result = System.BitConverter.ToString(hash_byte);
  782.  
  783. result = result.Replace("-", "");
  784. return result;
  785. }
  786. #endregion
  787.  
  788. #region SHA256加密算法
  789.  
  790. /// <summary>
  791. /// SHA256函数
  792. /// </summary>
  793. /// <param name="str">原始字符串</param>
  794. /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
  795. public static string SHA256(string str)
  796. {
  797. byte[] SHA256Data = Encoding.UTF8.GetBytes(str);
  798. SHA256Managed Sha256 = new SHA256Managed();
  799. byte[] Result = Sha256.ComputeHash(SHA256Data);
  800. return Convert.ToBase64String(Result); //返回长度为44字节的字符串
  801. }
  802. #endregion
  803.  
  804. #region RC4加密 解密
  805.  
  806. /// <summary>RC4加密算法
  807. /// 返回进过rc4加密过的字符
  808. /// </summary>
  809. /// <param name="str">被加密的字符</param>
  810. /// <param name="ckey">密钥</param>
  811. public static string EncryptRC4wq(string str, string ckey)
  812. {
  813. int[] s = new int[];
  814. for (int i = ; i < ; i++)
  815. {
  816. s[i] = i;
  817. }
  818. //密钥转数组
  819. char[] keys = ckey.ToCharArray();//密钥转字符数组
  820. int[] key = new int[keys.Length];
  821. for (int i = ; i < keys.Length; i++)
  822. {
  823. key[i] = keys[i];
  824. }
  825. //明文转数组
  826. char[] datas = str.ToCharArray();
  827. int[] mingwen = new int[datas.Length];
  828. for (int i = ; i < datas.Length; i++)
  829. {
  830. mingwen[i] = datas[i];
  831. }
  832.  
  833. //通过循环得到256位的数组(密钥)
  834. int j = ;
  835. int k = ;
  836. int length = key.Length;
  837. int a;
  838. for (int i = ; i < ; i++)
  839. {
  840. a = s[i];
  841. j = (j + a + key[k]);
  842. if (j >= )
  843. {
  844. j = j % ;
  845. }
  846. s[i] = s[j];
  847. s[j] = a;
  848. if (++k >= length)
  849. {
  850. k = ;
  851. }
  852. }
  853. //根据上面的256的密钥数组 和 明文得到密文数组
  854. int x = , y = , a2, b, c;
  855. int length2 = mingwen.Length;
  856. int[] miwen = new int[length2];
  857. for (int i = ; i < length2; i++)
  858. {
  859. x = x + ;
  860. x = x % ;
  861. a2 = s[x];
  862. y = y + a2;
  863. y = y % ;
  864. s[x] = b = s[y];
  865. s[y] = a2;
  866. c = a2 + b;
  867. c = c % ;
  868. miwen[i] = mingwen[i] ^ s[c];
  869. }
  870. //密文数组转密文字符
  871. char[] mi = new char[miwen.Length];
  872. for (int i = ; i < miwen.Length; i++)
  873. {
  874. mi[i] = (char)miwen[i];
  875. }
  876. string miwenstr = new string(mi);
  877. return miwenstr;
  878. }
  879.  
  880. /// <summary>RC4解密算法
  881. /// 返回进过rc4解密过的字符
  882. /// </summary>
  883. /// <param name="str">被解密的字符</param>
  884. /// <param name="ckey">密钥</param>
  885. public static string DecryptRC4wq(string str, string ckey)
  886. {
  887. int[] s = new int[];
  888. for (int i = ; i < ; i++)
  889. {
  890. s[i] = i;
  891. }
  892. //密钥转数组
  893. char[] keys = ckey.ToCharArray();//密钥转字符数组
  894. int[] key = new int[keys.Length];
  895. for (int i = ; i < keys.Length; i++)
  896. {
  897. key[i] = keys[i];
  898. }
  899. //密文转数组
  900. char[] datas = str.ToCharArray();
  901. int[] miwen = new int[datas.Length];
  902. for (int i = ; i < datas.Length; i++)
  903. {
  904. miwen[i] = datas[i];
  905. }
  906.  
  907. //通过循环得到256位的数组(密钥)
  908. int j = ;
  909. int k = ;
  910. int length = key.Length;
  911. int a;
  912. for (int i = ; i < ; i++)
  913. {
  914. a = s[i];
  915. j = (j + a + key[k]);
  916. if (j >= )
  917. {
  918. j = j % ;
  919. }
  920. s[i] = s[j];
  921. s[j] = a;
  922. if (++k >= length)
  923. {
  924. k = ;
  925. }
  926. }
  927. //根据上面的256的密钥数组 和 密文得到明文数组
  928. int x = , y = , a2, b, c;
  929. int length2 = miwen.Length;
  930. int[] mingwen = new int[length2];
  931. for (int i = ; i < length2; i++)
  932. {
  933. x = x + ;
  934. x = x % ;
  935. a2 = s[x];
  936. y = y + a2;
  937. y = y % ;
  938. s[x] = b = s[y];
  939. s[y] = a2;
  940. c = a2 + b;
  941. c = c % ;
  942. mingwen[i] = miwen[i] ^ s[c];
  943. }
  944. //明文数组转明文字符
  945. char[] ming = new char[mingwen.Length];
  946. for (int i = ; i < mingwen.Length; i++)
  947. {
  948. ming[i] = (char)mingwen[i];
  949. }
  950. string mingwenstr = new string(ming);
  951. return mingwenstr;
  952. }
  953. #endregion
  954. }
  955. }

原文:https://www.cnblogs.com/gygang/p/8873702.html

C# 各种加密的更多相关文章

  1. 关于CryptoJS中md5加密以及aes加密的随笔

    最近项目中用到了各种加密,其中就包括从没有接触过得aes加密,因此从网上各种查,官方的一种说法: 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学 ...

  2. “不给力啊,老湿!”:RSA加密与破解

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 加密和解密是自古就有技术了.经常看到侦探电影的桥段,勇敢又机智的主角,拿着一长串毫 ...

  3. .NET 对接JAVA 使用Modulus,Exponent RSA 加密

    最近有一个工作是需要把数据用RSA发送给Java 虽然一开始标准公钥 net和Java  RSA填充的一些算法不一样 但是后来这个坑也补的差不多了 具体可以参考 http://www.cnblogs. ...

  4. AES加密

    package com.edu.hpu; import java.math.BigInteger; import java.security.MessageDigest; import java.se ...

  5. Android数据加密之MD5加密

    前言: 项目中无论是密码的存储或者说判断文件是否是同一文件,都会用到MD5算法,今天来总结一下MD5加密算法. 什么是MD5加密? MD5英文全称“Message-Digest Algorithm 5 ...

  6. PHP的学习--RSA加密解密

    PHP服务端与客户端交互或者提供开放API时,通常需要对敏感的数据进行加密,这时候rsa非对称加密就能派上用处了. 举个通俗易懂的例子,假设我们再登录一个网站,发送账号和密码,请求被拦截了. 密码没加 ...

  7. ASP.NET加密和解密数据库连接字符串

    大家知道,在应用程序中进行数据库操作需要连接字符串,而如果没有连接字符串,我们就无法在应用程序中完成检索数据,创建数据等一系列的数据库操作.当有人想要获取你程序中的数据库信息,他首先看到的可能会是We ...

  8. GPG终极指南(加密/签名)

    我们平时都听过非对称加密,公钥和私钥,签名验证,但这些证书都是怎么得到的呢?本篇文章会解答这些问题. 背景介绍 加密的一个简单但又实用的任务就是发送加密电子邮件.多年来,为电子邮件进行加密的标准一直是 ...

  9. RSA非对称加密,使用OpenSSL生成证书,iOS加密,java解密

    最近换了一份工作,工作了大概一个多月了吧.差不多得有两个月没有更新博客了吧.在新公司自己写了一个iOS的比较通用的可以架构一个中型应用的不算是框架的一个结构,并已经投入使用.哈哈 说说文章标题的相关的 ...

  10. C# salt+hash 加密

    一.先明确几个基本概念 1.伪随机数:pseudo-random number generators ,简称为:PRNGs,是计算机利用一定的算法来产生的.伪随机数并不是假随机 数,这里的" ...

随机推荐

  1. html audio标签 语法

    html audio标签 语法 audio标签的作用是什么? 作用:<audio> 标签定义声音,比如音乐和视频或其他音频资源,使用audio标签可以不用Flash插件就可以听音乐看视频, ...

  2. android stadio gradle问题

    https://www.jianshu.com/p/2bb0b6a7b479 https://www.jianshu.com/p/d175bef9770c Unable to resolve depe ...

  3. Ajax异步提交的步骤

    1.创建XHR对象 ,XMLHttpRequest(该对象负责悄悄滴与服务器进行交互): 2.设置响应函数/回调函数(响应函数规定对返回自服务器的信息如何进行处理): 3.通过xmlhttp.open ...

  4. 【转】ACM-数学总揽

    转自: http://www.aiuxian.com/article/p-2262657.html 数学也分好几大部分,各种算法也很多,一时不知从哪里开始,算了,具体的后面再说吧,鉴于最近遇到的有关博 ...

  5. windows powershell的常用命令

    cmd开启3389 如何用CMD开启3389与查看3389端口 开启 REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal /f 查端口 net ...

  6. [CSP-S模拟测试]:简单的括号序列(组合数)

    题目传送门(内部题82) 输入格式 一行一个字符串$ss$,保证$ss$中只包含$'('$和$')'$. 输出格式 一行一个整数,表示满足要求的子序列数对$10^9+7$的结果. 样例 样例输入1: ...

  7. json根据一个值返回对象,filter方法使用

    d = {   "student":[     {       "count":1000,       "stuList":[        ...

  8. 数据库MySQL(课下作业,必做) 20175225

    作业要求: 1.下载附件中的world.sql.zip, 参考http://www.cnblogs.com/rocedu/p/6371315.html#SECDB,导入world.sql,提交导入成功 ...

  9. 神经网络学习笔记一——Neural Network

    参考自http://deeplearning.stanford.edu/wiki/index.php/Neural_Networks 神经元模型 h(x)= f(W'x)f(z)一般会用sigmoid ...

  10. day64—ajax技术学习笔记

    转行学开发,代码100天——2018-05-19 Ajax技术学习笔记 AJAX = Asynchronous JavaScript and XML(异步的 JavaScript 和 XML).AJA ...