Encrypt.cs 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536
  1. using System;
  2. using System.Collections;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. namespace Masuit.Tools.Security
  7. {
  8. /// <summary>
  9. /// 常用的加密解密算法
  10. /// </summary>
  11. public static class Encrypt
  12. {
  13. #region DES对称加密解密
  14. /// <summary>
  15. /// 加密密钥,需要在config配置文件中AppSettings节点中配置desSecret值,若未配置,默认取“masuit”的MD5值
  16. /// </summary>
  17. public static string DefaultEncryptKey = "masuit".MDString2();
  18. /// <summary>
  19. /// 使用默认加密
  20. /// </summary>
  21. /// <param name="strText">被加密的字符串</param>
  22. /// <returns>加密后的数据</returns>
  23. public static string DesEncrypt(this string strText)
  24. {
  25. try
  26. {
  27. return DesEncrypt(strText, DefaultEncryptKey);
  28. }
  29. catch
  30. {
  31. return "";
  32. }
  33. }
  34. /// <summary>
  35. /// 使用默认解密
  36. /// </summary>
  37. /// <param name="strText">需要解密的 字符串</param>
  38. /// <returns>解密后的数据</returns>
  39. public static string DesDecrypt(this string strText)
  40. {
  41. try
  42. {
  43. return DesDecrypt(strText, DefaultEncryptKey);
  44. }
  45. catch
  46. {
  47. return "";
  48. }
  49. }
  50. /// <summary>
  51. /// 解密字符串
  52. /// 加密密钥必须为8位
  53. /// </summary>
  54. /// <param name="strText">被解密的字符串</param>
  55. /// <param name="strEncrKey">密钥</param>
  56. /// <returns>解密后的数据</returns>
  57. public static string DesEncrypt(this string strText, string strEncrKey)
  58. {
  59. if (strEncrKey.Length < 8)
  60. {
  61. throw new Exception("密钥长度无效,密钥必须是8位!");
  62. }
  63. StringBuilder ret = new StringBuilder();
  64. DESCryptoServiceProvider des = new DESCryptoServiceProvider();
  65. byte[] inputByteArray = Encoding.Default.GetBytes(strText);
  66. des.Key = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
  67. des.IV = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
  68. MemoryStream ms = new MemoryStream();
  69. CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  70. cs.Write(inputByteArray, 0, inputByteArray.Length);
  71. cs.FlushFinalBlock();
  72. foreach (byte b in ms.ToArray())
  73. {
  74. ret.AppendFormat($"{b:X2}");
  75. }
  76. return ret.ToString();
  77. }
  78. /// <summary>
  79. /// DES加密文件
  80. /// </summary>
  81. /// <param name="fin">文件输入流</param>
  82. /// <param name="outFilePath">文件输出路径</param>
  83. /// <param name="strEncrKey">加密密钥</param>
  84. public static void DesEncrypt(this FileStream fin, string outFilePath, string strEncrKey)
  85. {
  86. byte[] iv =
  87. {
  88. 0x12,
  89. 0x34,
  90. 0x56,
  91. 0x78,
  92. 0x90,
  93. 0xAB,
  94. 0xCD,
  95. 0xEF
  96. };
  97. var byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
  98. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  99. fout.SetLength(0);
  100. byte[] bin = new byte[100];
  101. long rdlen = 0;
  102. long totlen = fin.Length;
  103. DES des = new DESCryptoServiceProvider();
  104. var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
  105. while (rdlen < totlen)
  106. {
  107. var len = fin.Read(bin, 0, 100);
  108. encStream.Write(bin, 0, len);
  109. rdlen += len;
  110. }
  111. }
  112. /// <summary>
  113. /// DES解密文件
  114. /// </summary>
  115. /// <param name="fin">输入文件流</param>
  116. /// <param name="outFilePath">文件输出路径</param>
  117. /// <param name="sDecrKey">解密密钥</param>
  118. public static void DesDecrypt(this FileStream fin, string outFilePath, string sDecrKey)
  119. {
  120. byte[] iv =
  121. {
  122. 0x12,
  123. 0x34,
  124. 0x56,
  125. 0x78,
  126. 0x90,
  127. 0xAB,
  128. 0xCD,
  129. 0xEF
  130. };
  131. var byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
  132. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  133. fout.SetLength(0);
  134. byte[] bin = new byte[100];
  135. long rdlen = 0;
  136. long totlen = fin.Length;
  137. DES des = new DESCryptoServiceProvider();
  138. var encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
  139. while (rdlen < totlen)
  140. {
  141. var len = fin.Read(bin, 0, 100);
  142. encStream.Write(bin, 0, len);
  143. rdlen += len;
  144. }
  145. }
  146. /// <summary>
  147. /// DES解密算法
  148. /// 密钥为8位
  149. /// </summary>
  150. /// <param name="pToDecrypt">需要解密的字符串</param>
  151. /// <param name="sKey">密钥</param>
  152. /// <returns>解密后的数据</returns>
  153. public static string DesDecrypt(this string pToDecrypt, string sKey)
  154. {
  155. if (sKey.Length < 8)
  156. {
  157. throw new Exception("密钥长度无效,密钥必须是8位!");
  158. }
  159. var ms = new MemoryStream();
  160. var des = new DESCryptoServiceProvider();
  161. var inputByteArray = new byte[pToDecrypt.Length / 2];
  162. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  163. {
  164. int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
  165. inputByteArray[x] = (byte)i;
  166. }
  167. des.Key = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
  168. des.IV = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
  169. var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  170. cs.Write(inputByteArray, 0, inputByteArray.Length);
  171. cs.FlushFinalBlock();
  172. return Encoding.Default.GetString(ms.ToArray());
  173. }
  174. #endregion
  175. #region 对称加密算法AES RijndaelManaged加密解密
  176. private static readonly string Default_AES_Key = "@#kim123";
  177. private static byte[] Keys =
  178. {
  179. 0x41,
  180. 0x72,
  181. 0x65,
  182. 0x79,
  183. 0x6F,
  184. 0x75,
  185. 0x6D,
  186. 0x79,
  187. 0x53,
  188. 0x6E,
  189. 0x6F,
  190. 0x77,
  191. 0x6D,
  192. 0x61,
  193. 0x6E,
  194. 0x3F
  195. };
  196. /// <summary>
  197. /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
  198. /// </summary>
  199. /// <param name="encryptString">待加密字符串</param>
  200. /// <returns>加密结果字符串</returns>
  201. public static string AESEncrypt(this string encryptString)
  202. {
  203. return AESEncrypt(encryptString, Default_AES_Key);
  204. }
  205. /// <summary>
  206. /// 对称加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是块式加密算法)
  207. /// </summary>
  208. /// <param name="encryptString">待加密字符串</param>
  209. /// <param name="encryptKey">加密密钥,须半角字符</param>
  210. /// <returns>加密结果字符串</returns>
  211. public static string AESEncrypt(this string encryptString, string encryptKey)
  212. {
  213. encryptKey = GetSubString(encryptKey, 32, "");
  214. encryptKey = encryptKey.PadRight(32, ' ');
  215. var rijndaelProvider = new RijndaelManaged
  216. {
  217. Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32)),
  218. IV = Keys
  219. };
  220. ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
  221. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  222. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  223. return Convert.ToBase64String(encryptedData);
  224. }
  225. /// <summary>
  226. /// 对称加密算法AES RijndaelManaged解密字符串
  227. /// </summary>
  228. /// <param name="decryptString">待解密的字符串</param>
  229. /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
  230. public static string AESDecrypt(this string decryptString)
  231. {
  232. return AESDecrypt(decryptString, Default_AES_Key);
  233. }
  234. /// <summary>
  235. /// 对称加密算法AES RijndaelManaged解密字符串
  236. /// </summary>
  237. /// <param name="decryptString">待解密的字符串</param>
  238. /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
  239. /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
  240. public static string AESDecrypt(this string decryptString, string decryptKey)
  241. {
  242. try
  243. {
  244. decryptKey = GetSubString(decryptKey, 32, "");
  245. decryptKey = decryptKey.PadRight(32, ' ');
  246. var rijndaelProvider = new RijndaelManaged()
  247. {
  248. Key = Encoding.UTF8.GetBytes(decryptKey),
  249. IV = Keys
  250. };
  251. ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
  252. byte[] inputData = Convert.FromBase64String(decryptString);
  253. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  254. return Encoding.UTF8.GetString(decryptedData);
  255. }
  256. catch
  257. {
  258. return string.Empty;
  259. }
  260. }
  261. /// <summary>
  262. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  263. /// </summary>
  264. /// <param name="sourceString">源字符串</param>
  265. /// <param name="length">所取字符串字节长度</param>
  266. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  267. /// <returns>某字符串的一部分</returns>
  268. private static string GetSubString(this string sourceString, int length, string tailString)
  269. {
  270. return GetSubString(sourceString, 0, length, tailString);
  271. }
  272. /// <summary>
  273. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  274. /// </summary>
  275. /// <param name="sourceString">源字符串</param>
  276. /// <param name="startIndex">索引位置,以0开始</param>
  277. /// <param name="length">所取字符串字节长度</param>
  278. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  279. /// <returns>某字符串的一部分</returns>
  280. private static string GetSubString(this string sourceString, int startIndex, int length, string tailString)
  281. {
  282. //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
  283. if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") || System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
  284. {
  285. //当截取的起始位置超出字段串长度时
  286. if (startIndex >= sourceString.Length)
  287. {
  288. return string.Empty;
  289. }
  290. return sourceString.Substring(startIndex, length + startIndex > sourceString.Length ? (sourceString.Length - startIndex) : length);
  291. }
  292. //中文字符,如"中国人民abcd123"
  293. if (length <= 0)
  294. {
  295. return string.Empty;
  296. }
  297. byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
  298. //当字符串长度大于起始位置
  299. if (bytesSource.Length > startIndex)
  300. {
  301. int endIndex = bytesSource.Length;
  302. //当要截取的长度在字符串的有效长度范围内
  303. if (bytesSource.Length > (startIndex + length))
  304. {
  305. endIndex = length + startIndex;
  306. }
  307. else
  308. {
  309. //当不在有效范围内时,只取到字符串的结尾
  310. length = bytesSource.Length - startIndex;
  311. tailString = "";
  312. }
  313. var anResultFlag = new int[length];
  314. int nFlag = 0;
  315. //字节大于127为双字节字符
  316. for (int i = startIndex; i < endIndex; i++)
  317. {
  318. if (bytesSource[i] > 127)
  319. {
  320. nFlag++;
  321. if (nFlag == 3)
  322. {
  323. nFlag = 1;
  324. }
  325. }
  326. else
  327. {
  328. nFlag = 0;
  329. }
  330. anResultFlag[i] = nFlag;
  331. }
  332. //最后一个字节为双字节字符的一半
  333. if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
  334. {
  335. length++;
  336. }
  337. byte[] bsResult = new byte[length];
  338. Array.Copy(bytesSource, startIndex, bsResult, 0, length);
  339. var myResult = Encoding.Default.GetString(bsResult);
  340. myResult += tailString;
  341. return myResult;
  342. }
  343. return string.Empty;
  344. }
  345. /// <summary>
  346. /// 加密文件流
  347. /// </summary>
  348. /// <param name="fs">需要加密的文件流</param>
  349. /// <param name="decryptKey">加密密钥</param>
  350. /// <returns>加密流</returns>
  351. public static CryptoStream AESEncryptStrream(this FileStream fs, string decryptKey)
  352. {
  353. decryptKey = GetSubString(decryptKey, 32, "");
  354. decryptKey = decryptKey.PadRight(32, ' ');
  355. var rijndaelProvider = new RijndaelManaged()
  356. {
  357. Key = Encoding.UTF8.GetBytes(decryptKey),
  358. IV = Keys
  359. };
  360. ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
  361. return new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
  362. }
  363. /// <summary>
  364. /// 解密文件流
  365. /// </summary>
  366. /// <param name="fs">需要解密的文件流</param>
  367. /// <param name="decryptKey">解密密钥</param>
  368. /// <returns>加密流</returns>
  369. public static CryptoStream AESDecryptStream(this FileStream fs, string decryptKey)
  370. {
  371. decryptKey = GetSubString(decryptKey, 32, "");
  372. decryptKey = decryptKey.PadRight(32, ' ');
  373. var rijndaelProvider = new RijndaelManaged()
  374. {
  375. Key = Encoding.UTF8.GetBytes(decryptKey),
  376. IV = Keys
  377. };
  378. var decrypto = rijndaelProvider.CreateDecryptor();
  379. return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
  380. }
  381. /// <summary>
  382. /// 对指定文件AES加密
  383. /// </summary>
  384. /// <param name="input">源文件流</param>
  385. /// <param name="outputPath">输出文件路径</param>
  386. public static void AESEncryptFile(this FileStream input, string outputPath)
  387. {
  388. using var fren = new FileStream(outputPath, FileMode.Create);
  389. var enfr = AESEncryptStrream(fren, Default_AES_Key);
  390. byte[] bytearrayinput = new byte[input.Length];
  391. input.Read(bytearrayinput, 0, bytearrayinput.Length);
  392. enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
  393. }
  394. /// <summary>
  395. /// 对指定的文件AES解密
  396. /// </summary>
  397. /// <param name="input">源文件流</param>
  398. /// <param name="outputPath">输出文件路径</param>
  399. public static void AESDecryptFile(this FileStream input, string outputPath)
  400. {
  401. FileStream frde = new FileStream(outputPath, FileMode.Create);
  402. CryptoStream defr = AESDecryptStream(input, Default_AES_Key);
  403. byte[] bytearrayoutput = new byte[1024];
  404. while (true)
  405. {
  406. var count = defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
  407. frde.Write(bytearrayoutput, 0, count);
  408. if (count < bytearrayoutput.Length)
  409. {
  410. break;
  411. }
  412. }
  413. }
  414. #endregion
  415. #region Base64加密解密
  416. /// <summary>
  417. /// Base64加密
  418. /// </summary>
  419. /// <param name="str">需要加密的字符串</param>
  420. /// <returns>加密后的数据</returns>
  421. public static string Base64Encrypt(this string str)
  422. {
  423. byte[] encbuff = Encoding.UTF8.GetBytes(str);
  424. return Convert.ToBase64String(encbuff);
  425. }
  426. /// <summary>
  427. /// Base64解密
  428. /// </summary>
  429. /// <param name="str">需要解密的字符串</param>
  430. /// <returns>解密后的数据</returns>
  431. public static string Base64Decrypt(this string str)
  432. {
  433. byte[] decbuff = Convert.FromBase64String(str);
  434. return Encoding.UTF8.GetString(decbuff);
  435. }
  436. #endregion
  437. #region MD5加密
  438. /// <summary>
  439. /// MD5加密
  440. /// </summary>
  441. /// <param name="strText">原数据</param>
  442. /// <returns>MD5字符串</returns>
  443. public static string MD5Encrypt(this string strText)
  444. {
  445. MD5 md5 = new MD5CryptoServiceProvider();
  446. byte[] result = md5.ComputeHash(Encoding.Default.GetBytes(strText));
  447. return Encoding.Default.GetString(result);
  448. }
  449. #endregion
  450. /// <summary>
  451. /// SHA256函数
  452. /// </summary>
  453. /// <param name="str">原始字符串</param>
  454. /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
  455. public static string SHA256(this string str)
  456. {
  457. byte[] sha256Data = Encoding.UTF8.GetBytes(str);
  458. var sha256 = new SHA256Managed();
  459. byte[] result = sha256.ComputeHash(sha256Data);
  460. return Convert.ToBase64String(result); //返回长度为44字节的字符串
  461. }
  462. #region 创建Key
  463. /// <summary>
  464. /// 创建Key
  465. /// </summary>
  466. /// <returns>密钥</returns>
  467. public static string GenerateKey()
  468. {
  469. var desCrypto = (DESCryptoServiceProvider)DES.Create();
  470. return Encoding.ASCII.GetString(desCrypto.Key);
  471. }
  472. #endregion
  473. #region MD5加密
  474. /// <summary>
  475. /// MD5加密
  476. /// </summary>
  477. /// <param name="pToEncrypt">加密字符串</param>
  478. /// <param name="sKey">密钥Key</param>
  479. /// <returns>加密后的字符串</returns>
  480. public static string MD5Encrypt(this string pToEncrypt, string sKey)
  481. {
  482. var des = new DESCryptoServiceProvider();
  483. var inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
  484. des.Key = Encoding.ASCII.GetBytes(sKey);
  485. des.IV = Encoding.ASCII.GetBytes(sKey);
  486. var ms = new MemoryStream();
  487. var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  488. cs.Write(inputByteArray, 0, inputByteArray.Length);
  489. cs.FlushFinalBlock();
  490. var ret = new StringBuilder();
  491. foreach (var b in ms.ToArray())
  492. {
  493. ret.AppendFormat("{0:X2}", b);
  494. }
  495. ret.ToString();
  496. return ret.ToString();
  497. }
  498. #endregion
  499. #region MD5解密
  500. /// <summary>
  501. /// MD5解密
  502. /// </summary>
  503. /// <param name="pToDecrypt">解密字符串</param>
  504. /// <param name="sKey">密钥Key</param>
  505. /// <returns>解密后的数据</returns>
  506. public static string MD5Decrypt(this string pToDecrypt, string sKey)
  507. {
  508. var des = new DESCryptoServiceProvider();
  509. var inputByteArray = new byte[pToDecrypt.Length / 2];
  510. for (var x = 0; x < pToDecrypt.Length / 2; x++)
  511. {
  512. var i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
  513. inputByteArray[x] = (byte)i;
  514. }
  515. des.Key = Encoding.ASCII.GetBytes(sKey);
  516. des.IV = Encoding.ASCII.GetBytes(sKey);
  517. var ms = new MemoryStream();
  518. var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  519. cs.Write(inputByteArray, 0, inputByteArray.Length);
  520. cs.FlushFinalBlock();
  521. return Encoding.Default.GetString(ms.ToArray());
  522. }
  523. #endregion
  524. #region MD5加密算法
  525. //number of bits to rotate in tranforming
  526. private const int S11 = 7;
  527. private const int S12 = 12;
  528. private const int S13 = 17;
  529. private const int S14 = 22;
  530. private const int S21 = 5;
  531. private const int S22 = 9;
  532. private const int S23 = 14;
  533. private const int S24 = 20;
  534. private const int S31 = 4;
  535. private const int S32 = 11;
  536. private const int S33 = 16;
  537. private const int S34 = 23;
  538. private const int S41 = 6;
  539. private const int S42 = 10;
  540. private const int S43 = 15;
  541. private const int S44 = 21;
  542. //static state variables
  543. private static uint A;
  544. private static uint B;
  545. private static uint C;
  546. private static uint D;
  547. private static uint F(uint x, uint y, uint z)
  548. {
  549. return (x & y) | (~x & z);
  550. }
  551. private static uint G(uint x, uint y, uint z)
  552. {
  553. return (x & z) | (y & ~z);
  554. }
  555. private static uint H(uint x, uint y, uint z)
  556. {
  557. return x ^ y ^ z;
  558. }
  559. private static uint I(uint x, uint y, uint z)
  560. {
  561. return y ^ (x | ~z);
  562. }
  563. private static void FF(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
  564. {
  565. a = a + F(b, c, d) + mj + ti;
  566. a = (a << s) | (a >> (32 - s));
  567. a += b;
  568. }
  569. private static void GG(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
  570. {
  571. a = a + G(b, c, d) + mj + ti;
  572. a = (a << s) | (a >> (32 - s));
  573. a += b;
  574. }
  575. private static void HH(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
  576. {
  577. a = a + H(b, c, d) + mj + ti;
  578. a = (a << s) | (a >> (32 - s));
  579. a += b;
  580. }
  581. private static void II(ref uint a, uint b, uint c, uint d, uint mj, int s, uint ti)
  582. {
  583. a = a + I(b, c, d) + mj + ti;
  584. a = (a << s) | (a >> (32 - s));
  585. a += b;
  586. }
  587. private static void MD5_Init()
  588. {
  589. A = 0x67452301; //in memory, this is 0x01234567
  590. B = 0xefcdab89; //in memory, this is 0x89abcdef
  591. C = 0x98badcfe; //in memory, this is 0xfedcba98
  592. D = 0x10325476; //in memory, this is 0x76543210
  593. }
  594. private static uint[] MD5_Append(byte[] input)
  595. {
  596. int zeros;
  597. var ones = 1;
  598. int size;
  599. var n = input.Length;
  600. var m = n % 64;
  601. if (m < 56)
  602. {
  603. zeros = 55 - m;
  604. size = n - m + 64;
  605. }
  606. else if (m == 56)
  607. {
  608. zeros = 0;
  609. ones = 0;
  610. size = n + 8;
  611. }
  612. else
  613. {
  614. zeros = 63 - m + 56;
  615. size = n + 64 - m + 64;
  616. }
  617. var bs = new ArrayList(input);
  618. if (ones == 1)
  619. bs.Add((byte)0x80); // 0x80 = $10000000
  620. for (var i = 0; i < zeros; i++)
  621. bs.Add((byte)0);
  622. var N = (ulong)n * 8;
  623. var h1 = (byte)(N & 0xFF);
  624. var h2 = (byte)((N >> 8) & 0xFF);
  625. var h3 = (byte)((N >> 16) & 0xFF);
  626. var h4 = (byte)((N >> 24) & 0xFF);
  627. var h5 = (byte)((N >> 32) & 0xFF);
  628. var h6 = (byte)((N >> 40) & 0xFF);
  629. var h7 = (byte)((N >> 48) & 0xFF);
  630. var h8 = (byte)(N >> 56);
  631. bs.Add(h1);
  632. bs.Add(h2);
  633. bs.Add(h3);
  634. bs.Add(h4);
  635. bs.Add(h5);
  636. bs.Add(h6);
  637. bs.Add(h7);
  638. bs.Add(h8);
  639. var ts = (byte[])bs.ToArray(typeof(byte));
  640. /* Decodes input (byte[]) into output (UInt32[]). Assumes len is
  641. * a multiple of 4.
  642. */
  643. var output = new uint[size / 4];
  644. for (long i = 0, j = 0; i < size; j++, i += 4)
  645. output[j] = (uint)(ts[i] | (ts[i + 1] << 8) | (ts[i + 2] << 16) | (ts[i + 3] << 24));
  646. return output;
  647. }
  648. private static uint[] MD5_Trasform(uint[] x)
  649. {
  650. uint a, b, c, d;
  651. for (var k = 0; k < x.Length; k += 16)
  652. {
  653. a = A;
  654. b = B;
  655. c = C;
  656. d = D;
  657. /* Round 1 */
  658. FF(ref a, b, c, d, x[k + 0], S11, 0xd76aa478); /* 1 */
  659. FF(ref d, a, b, c, x[k + 1], S12, 0xe8c7b756); /* 2 */
  660. FF(ref c, d, a, b, x[k + 2], S13, 0x242070db); /* 3 */
  661. FF(ref b, c, d, a, x[k + 3], S14, 0xc1bdceee); /* 4 */
  662. FF(ref a, b, c, d, x[k + 4], S11, 0xf57c0faf); /* 5 */
  663. FF(ref d, a, b, c, x[k + 5], S12, 0x4787c62a); /* 6 */
  664. FF(ref c, d, a, b, x[k + 6], S13, 0xa8304613); /* 7 */
  665. FF(ref b, c, d, a, x[k + 7], S14, 0xfd469501); /* 8 */
  666. FF(ref a, b, c, d, x[k + 8], S11, 0x698098d8); /* 9 */
  667. FF(ref d, a, b, c, x[k + 9], S12, 0x8b44f7af); /* 10 */
  668. FF(ref c, d, a, b, x[k + 10], S13, 0xffff5bb1); /* 11 */
  669. FF(ref b, c, d, a, x[k + 11], S14, 0x895cd7be); /* 12 */
  670. FF(ref a, b, c, d, x[k + 12], S11, 0x6b901122); /* 13 */
  671. FF(ref d, a, b, c, x[k + 13], S12, 0xfd987193); /* 14 */
  672. FF(ref c, d, a, b, x[k + 14], S13, 0xa679438e); /* 15 */
  673. FF(ref b, c, d, a, x[k + 15], S14, 0x49b40821); /* 16 */
  674. /* Round 2 */
  675. GG(ref a, b, c, d, x[k + 1], S21, 0xf61e2562); /* 17 */
  676. GG(ref d, a, b, c, x[k + 6], S22, 0xc040b340); /* 18 */
  677. GG(ref c, d, a, b, x[k + 11], S23, 0x265e5a51); /* 19 */
  678. GG(ref b, c, d, a, x[k + 0], S24, 0xe9b6c7aa); /* 20 */
  679. GG(ref a, b, c, d, x[k + 5], S21, 0xd62f105d); /* 21 */
  680. GG(ref d, a, b, c, x[k + 10], S22, 0x2441453); /* 22 */
  681. GG(ref c, d, a, b, x[k + 15], S23, 0xd8a1e681); /* 23 */
  682. GG(ref b, c, d, a, x[k + 4], S24, 0xe7d3fbc8); /* 24 */
  683. GG(ref a, b, c, d, x[k + 9], S21, 0x21e1cde6); /* 25 */
  684. GG(ref d, a, b, c, x[k + 14], S22, 0xc33707d6); /* 26 */
  685. GG(ref c, d, a, b, x[k + 3], S23, 0xf4d50d87); /* 27 */
  686. GG(ref b, c, d, a, x[k + 8], S24, 0x455a14ed); /* 28 */
  687. GG(ref a, b, c, d, x[k + 13], S21, 0xa9e3e905); /* 29 */
  688. GG(ref d, a, b, c, x[k + 2], S22, 0xfcefa3f8); /* 30 */
  689. GG(ref c, d, a, b, x[k + 7], S23, 0x676f02d9); /* 31 */
  690. GG(ref b, c, d, a, x[k + 12], S24, 0x8d2a4c8a); /* 32 */
  691. /* Round 3 */
  692. HH(ref a, b, c, d, x[k + 5], S31, 0xfffa3942); /* 33 */
  693. HH(ref d, a, b, c, x[k + 8], S32, 0x8771f681); /* 34 */
  694. HH(ref c, d, a, b, x[k + 11], S33, 0x6d9d6122); /* 35 */
  695. HH(ref b, c, d, a, x[k + 14], S34, 0xfde5380c); /* 36 */
  696. HH(ref a, b, c, d, x[k + 1], S31, 0xa4beea44); /* 37 */
  697. HH(ref d, a, b, c, x[k + 4], S32, 0x4bdecfa9); /* 38 */
  698. HH(ref c, d, a, b, x[k + 7], S33, 0xf6bb4b60); /* 39 */
  699. HH(ref b, c, d, a, x[k + 10], S34, 0xbebfbc70); /* 40 */
  700. HH(ref a, b, c, d, x[k + 13], S31, 0x289b7ec6); /* 41 */
  701. HH(ref d, a, b, c, x[k + 0], S32, 0xeaa127fa); /* 42 */
  702. HH(ref c, d, a, b, x[k + 3], S33, 0xd4ef3085); /* 43 */
  703. HH(ref b, c, d, a, x[k + 6], S34, 0x4881d05); /* 44 */
  704. HH(ref a, b, c, d, x[k + 9], S31, 0xd9d4d039); /* 45 */
  705. HH(ref d, a, b, c, x[k + 12], S32, 0xe6db99e5); /* 46 */
  706. HH(ref c, d, a, b, x[k + 15], S33, 0x1fa27cf8); /* 47 */
  707. HH(ref b, c, d, a, x[k + 2], S34, 0xc4ac5665); /* 48 */
  708. /* Round 4 */
  709. II(ref a, b, c, d, x[k + 0], S41, 0xf4292244); /* 49 */
  710. II(ref d, a, b, c, x[k + 7], S42, 0x432aff97); /* 50 */
  711. II(ref c, d, a, b, x[k + 14], S43, 0xab9423a7); /* 51 */
  712. II(ref b, c, d, a, x[k + 5], S44, 0xfc93a039); /* 52 */
  713. II(ref a, b, c, d, x[k + 12], S41, 0x655b59c3); /* 53 */
  714. II(ref d, a, b, c, x[k + 3], S42, 0x8f0ccc92); /* 54 */
  715. II(ref c, d, a, b, x[k + 10], S43, 0xffeff47d); /* 55 */
  716. II(ref b, c, d, a, x[k + 1], S44, 0x85845dd1); /* 56 */
  717. II(ref a, b, c, d, x[k + 8], S41, 0x6fa87e4f); /* 57 */
  718. II(ref d, a, b, c, x[k + 15], S42, 0xfe2ce6e0); /* 58 */
  719. II(ref c, d, a, b, x[k + 6], S43, 0xa3014314); /* 59 */
  720. II(ref b, c, d, a, x[k + 13], S44, 0x4e0811a1); /* 60 */
  721. II(ref a, b, c, d, x[k + 4], S41, 0xf7537e82); /* 61 */
  722. II(ref d, a, b, c, x[k + 11], S42, 0xbd3af235); /* 62 */
  723. II(ref c, d, a, b, x[k + 2], S43, 0x2ad7d2bb); /* 63 */
  724. II(ref b, c, d, a, x[k + 9], S44, 0xeb86d391); /* 64 */
  725. A += a;
  726. B += b;
  727. C += c;
  728. D += d;
  729. }
  730. return new[]
  731. {
  732. A,
  733. B,
  734. C,
  735. D
  736. };
  737. }
  738. #region MD5对数组数据加密
  739. /// <summary>
  740. /// MD5对数组数据加密
  741. /// </summary>
  742. /// <param name="input">包含需要加密的数据的数组</param>
  743. /// <returns>加密后的字节流</returns>
  744. public static byte[] MD5Array(this byte[] input)
  745. {
  746. MD5_Init();
  747. var block = MD5_Append(input);
  748. var bits = MD5_Trasform(block);
  749. var output = new byte[bits.Length * 4];
  750. for (int i = 0, j = 0; i < bits.Length; i++, j += 4)
  751. {
  752. output[j] = (byte)(bits[i] & 0xff);
  753. output[j + 1] = (byte)((bits[i] >> 8) & 0xff);
  754. output[j + 2] = (byte)((bits[i] >> 16) & 0xff);
  755. output[j + 3] = (byte)((bits[i] >> 24) & 0xff);
  756. }
  757. return output;
  758. }
  759. #endregion
  760. #region 获取数组的Hex值
  761. /// <summary>
  762. /// 获取数组的Hex值
  763. /// </summary>
  764. /// <param name="array">需要求Hex值的数组</param>
  765. /// <param name="uppercase">是否转大写</param>
  766. /// <returns>字节数组的16进制表示</returns>
  767. public static string ArrayToHexString(this byte[] array, bool uppercase)
  768. {
  769. var hexString = "";
  770. var format = "x2";
  771. if (uppercase)
  772. format = "X2";
  773. foreach (var b in array)
  774. hexString += b.ToString(format);
  775. return hexString;
  776. }
  777. #endregion
  778. #region 对字符串进行MD5加密
  779. /// <summary>
  780. /// 对字符串进行MD5加密
  781. /// </summary>
  782. /// <param name="message">需要加密的字符串</param>
  783. /// <returns>加密后的结果</returns>
  784. public static string MDString(this string message)
  785. {
  786. var c = message.ToCharArray();
  787. var b = new byte[c.Length];
  788. for (var i = 0; i < c.Length; i++)
  789. b[i] = (byte)c[i];
  790. var digest = MD5Array(b);
  791. return ArrayToHexString(digest, false);
  792. }
  793. /// <summary>
  794. /// 对字符串进行MD5二次加密
  795. /// </summary>
  796. /// <param name="message">需要加密的字符串</param>
  797. /// <returns>加密后的结果</returns>
  798. public static string MDString2(this string message) => MDString(MDString(message));
  799. /// <summary>
  800. /// MD5 三次加密算法
  801. /// </summary>
  802. /// <param name="s">需要加密的字符串</param>
  803. /// <returns>MD5字符串</returns>
  804. public static string MDString3(this string s)
  805. {
  806. MD5 md5 = MD5.Create();
  807. byte[] bytes = Encoding.ASCII.GetBytes(s);
  808. byte[] bytes1 = md5.ComputeHash(bytes);
  809. byte[] bytes2 = md5.ComputeHash(bytes1);
  810. byte[] bytes3 = md5.ComputeHash(bytes2);
  811. StringBuilder sb = new StringBuilder();
  812. foreach (var item in bytes3)
  813. {
  814. sb.Append(item.ToString("x").PadLeft(2, '0'));
  815. }
  816. return sb.ToString();
  817. }
  818. /// <summary>
  819. /// 对字符串进行MD5加盐加密
  820. /// </summary>
  821. /// <param name="message">需要加密的字符串</param>
  822. /// <param name="salt">盐</param>
  823. /// <returns>加密后的结果</returns>
  824. public static string MDString(this string message, string salt) => MDString(message + salt);
  825. /// <summary>
  826. /// 对字符串进行MD5二次加盐加密
  827. /// </summary>
  828. /// <param name="message">需要加密的字符串</param>
  829. /// <param name="salt">盐</param>
  830. /// <returns>加密后的结果</returns>
  831. public static string MDString2(this string message, string salt) => MDString(MDString(message + salt), salt);
  832. /// <summary>
  833. /// MD5 三次加密算法
  834. /// </summary>
  835. /// <param name="s">需要加密的字符串</param>
  836. /// <param name="salt">盐</param>
  837. /// <returns>MD5字符串</returns>
  838. public static string MDString3(this string s, string salt)
  839. {
  840. MD5 md5 = MD5.Create();
  841. byte[] bytes = Encoding.ASCII.GetBytes(s + salt);
  842. byte[] bytes1 = md5.ComputeHash(bytes);
  843. byte[] bytes2 = md5.ComputeHash(bytes1);
  844. byte[] bytes3 = md5.ComputeHash(bytes2);
  845. StringBuilder sb = new StringBuilder();
  846. foreach (var item in bytes3)
  847. {
  848. sb.Append(item.ToString("x").PadLeft(2, '0'));
  849. }
  850. return sb.ToString();
  851. }
  852. #endregion
  853. #region 获取文件的MD5值
  854. /// <summary>
  855. /// 获取文件的MD5值
  856. /// </summary>
  857. /// <param name="fileName">需要求MD5值的文件的文件名及路径</param>
  858. /// <returns>MD5字符串</returns>
  859. public static string MDFile(this string fileName)
  860. {
  861. var fs = File.Open(fileName, FileMode.Open, FileAccess.Read);
  862. var array = new byte[fs.Length];
  863. fs.Read(array, 0, (int)fs.Length);
  864. var digest = MD5Array(array);
  865. fs.Close();
  866. return ArrayToHexString(digest, false);
  867. }
  868. #endregion
  869. #region 测试MD5加密算法的函数
  870. /// <summary>
  871. /// 测试MD5加密算法的函数
  872. /// </summary>
  873. /// <param name="message">需要加密的字符串</param>
  874. /// <returns>加密后的 数据</returns>
  875. private static string MD5Test(this string message)
  876. {
  877. return "rnMD5 (" + "message" + ") = " + MDString(message);
  878. }
  879. #endregion
  880. #region MD5加密算法测试用数据
  881. /// <summary>
  882. /// MD5加密算法测试用数据
  883. /// </summary>
  884. /// <returns> </returns>
  885. private static string TestSuite()
  886. {
  887. var s = "";
  888. s += MD5Test("");
  889. s += MD5Test("a");
  890. s += MD5Test("abc");
  891. s += MD5Test("message digest");
  892. s += MD5Test("abcdefghijklmnopqrstuvwxyz");
  893. s += MD5Test("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
  894. s += MD5Test("12345678901234567890123456789012345678901234567890123456789012345678901234567890");
  895. return s;
  896. }
  897. #endregion
  898. #endregion MD5加密算法
  899. }
  900. /// <summary>
  901. /// RC2加密解密算法
  902. /// </summary>
  903. public static class RC2
  904. {
  905. private static ASCIIEncoding _asciiEncoding;
  906. private static byte[] _iv;
  907. private static byte[] _key;
  908. private static RC2CryptoServiceProvider _rc2Csp;
  909. private static UnicodeEncoding _textConverter;
  910. static RC2()
  911. {
  912. InitializeComponent();
  913. }
  914. private static void InitializeComponent()
  915. {
  916. _key = new byte[]
  917. {
  918. 106,
  919. 51,
  920. 25,
  921. 141,
  922. 157,
  923. 142,
  924. 23,
  925. 111,
  926. 234,
  927. 159,
  928. 187,
  929. 154,
  930. 215,
  931. 34,
  932. 37,
  933. 204
  934. };
  935. _iv = new byte[]
  936. {
  937. 135,
  938. 186,
  939. 133,
  940. 136,
  941. 184,
  942. 149,
  943. 153,
  944. 144
  945. };
  946. _asciiEncoding = new ASCIIEncoding();
  947. _textConverter = new UnicodeEncoding();
  948. _rc2Csp = new RC2CryptoServiceProvider();
  949. }
  950. #region 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
  951. /// <summary>
  952. /// 新建一个大小为10261B的文件,以便将加密数据写入固定大小的文件。
  953. /// </summary>
  954. /// <param name="filePath">文件保存的地址,包含文件名</param>
  955. public static string InitBinFile(this string filePath)
  956. {
  957. var tmp = new byte[10261];
  958. try //创建文件流,将其内容全部写入0
  959. {
  960. var writeFileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None, 512, false);
  961. for (var i = 0; i < 10261; i++)
  962. tmp[i] = 0;
  963. writeFileStream.Write(tmp, 0, 10261);
  964. writeFileStream.Flush();
  965. writeFileStream.Close();
  966. }
  967. catch (IOException)
  968. {
  969. // MessageBox.Show("文件操作错误!", "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
  970. return "Error,file operation error!";
  971. }
  972. return "OK";
  973. }
  974. #endregion
  975. #region 将文本数据加密后写入一个文件
  976. /// <summary>
  977. /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
  978. /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
  979. /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
  980. /// </summary>
  981. /// <param name="toEncryptText">要加密的文本数据</param>
  982. /// <param name="filePath">要写入的文件</param>
  983. /// <param name="dataIndex">写入第几块,取值为1--10</param>
  984. /// <returns>是否操作成功</returns>
  985. public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex)
  986. {
  987. var r = false;
  988. if ((dataIndex > 10) && (dataIndex < 1))
  989. {
  990. return r;
  991. }
  992. //打开要写入的文件,主要是为了保持原文件的内容不丢失
  993. var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  994. var index = new byte[10261];
  995. //将读取的内容写到byte数组
  996. tmpFileStream.Read(index, 0, 10261);
  997. tmpFileStream.Close();
  998. //定义基本的加密转换运算
  999. var Encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
  1000. var msEncrypt = new MemoryStream();
  1001. //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
  1002. var csEncrypt = new CryptoStream(msEncrypt, Encryptor, CryptoStreamMode.Write);
  1003. //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
  1004. var tmp = _textConverter.GetBytes(toEncryptText);
  1005. //将tmp输入csEncrypt,将通过Encryptor来加密。
  1006. csEncrypt.Write(tmp, 0, tmp.Length);
  1007. //输出到msEnctypt
  1008. csEncrypt.FlushFinalBlock();
  1009. //将流转成byte[]
  1010. var encrypted = msEncrypt.ToArray();
  1011. if (encrypted.Length > 1024)
  1012. return false;
  1013. //得到加密后数据的大小,将结果存在指定的位置。
  1014. index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
  1015. index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
  1016. //将加密后的结果写入index(覆盖)
  1017. for (var i = 0; i < encrypted.Length; i++)
  1018. index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
  1019. //建立文件流
  1020. tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
  1021. //写文件
  1022. tmpFileStream.Write(index, 0, 10261);
  1023. tmpFileStream.Flush();
  1024. r = true;
  1025. tmpFileStream.Close();
  1026. return r;
  1027. }
  1028. #endregion
  1029. #region 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  1030. /// <summary>
  1031. /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  1032. /// </summary>
  1033. /// <param name="filePath">要解密的文件</param>
  1034. /// <param name="dataIndex">要从哪一个块中解密</param>
  1035. /// <returns>解密后的文本</returns>
  1036. public static string DecryptFromFile(this string filePath, int dataIndex)
  1037. {
  1038. var r = "";
  1039. if ((dataIndex > 10) && (dataIndex < 1))
  1040. {
  1041. return r;
  1042. }
  1043. var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1044. var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
  1045. var msDecrypt = new MemoryStream();
  1046. var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  1047. var index = new byte[10261];
  1048. tmpFileStream.Read(index, 0, 10261);
  1049. //var startIndex = 1024 * (dataIndex - 1) + 21;
  1050. var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
  1051. var tmp = new byte[count];
  1052. Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
  1053. csDecrypt.Write(tmp, 0, count);
  1054. csDecrypt.FlushFinalBlock();
  1055. var decrypted = msDecrypt.ToArray();
  1056. r = _textConverter.GetString(decrypted, 0, decrypted.Length);
  1057. tmpFileStream.Close();
  1058. return r;
  1059. }
  1060. #endregion
  1061. #region 将一段文本加密后保存到一个文件
  1062. /// <summary>
  1063. /// 将一段文本加密后保存到一个文件
  1064. /// </summary>
  1065. /// <param name="toEncryptText">要加密的文本数据</param>
  1066. /// <param name="filePath">要保存的文件</param>
  1067. /// <returns>是否加密成功</returns>
  1068. public static void EncryptToFile(this string toEncryptText, string filePath)
  1069. {
  1070. using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
  1071. using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
  1072. var msEncrypt = new MemoryStream();
  1073. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  1074. var tmp = _textConverter.GetBytes(toEncryptText);
  1075. csEncrypt.Write(tmp, 0, tmp.Length);
  1076. csEncrypt.FlushFinalBlock();
  1077. var encrypted = msEncrypt.ToArray();
  1078. tmpFileStream.Write(encrypted, 0, encrypted.Length);
  1079. }
  1080. #endregion
  1081. #region 将一个被加密的文件解密
  1082. /// <summary>
  1083. /// 将一个被加密的文件解密
  1084. /// </summary>
  1085. /// <param name="filePath">要解密的文件</param>
  1086. /// <returns>解密后的文本</returns>
  1087. public static string DecryptFromFile(this string filePath)
  1088. {
  1089. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1090. using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
  1091. var msDecrypt = new MemoryStream();
  1092. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  1093. var tmp = new byte[tmpFileStream.Length];
  1094. tmpFileStream.Read(tmp, 0, tmp.Length);
  1095. csDecrypt.Write(tmp, 0, tmp.Length);
  1096. csDecrypt.FlushFinalBlock();
  1097. var decrypted = msDecrypt.ToArray();
  1098. var r = _textConverter.GetString(decrypted, 0, decrypted.Length);
  1099. return r;
  1100. }
  1101. #endregion
  1102. #region 将文本数据加密后写入一个文件
  1103. /// <summary>
  1104. /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
  1105. /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
  1106. /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
  1107. /// </summary>
  1108. /// <param name="toEncryptText">要加密的文本数据</param>
  1109. /// <param name="filePath">要写入的文件</param>
  1110. /// <param name="dataIndex">写入第几块,取值为1--10</param>
  1111. /// <param name="IV">初始化向量</param>
  1112. /// <param name="Key">加密密匙</param>
  1113. /// <returns>是否操作成功</returns>
  1114. public static void EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
  1115. {
  1116. if ((dataIndex > 10) && (dataIndex < 1))
  1117. {
  1118. return;
  1119. }
  1120. //打开要写入的文件,主要是为了保持原文件的内容不丢失
  1121. using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1122. var index = new byte[10261];
  1123. //将读取的内容写到byte数组
  1124. fs.Read(index, 0, 10261);
  1125. //定义基本的加密转换运算
  1126. using var encryptor = _rc2Csp.CreateEncryptor(Key, IV);
  1127. var msEncrypt = new MemoryStream();
  1128. //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
  1129. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  1130. var tmp = _textConverter.GetBytes(toEncryptText);
  1131. //将tmp输入csEncrypt,将通过Encryptor来加密。
  1132. csEncrypt.Write(tmp, 0, tmp.Length);
  1133. //输出到msEnctypt
  1134. csEncrypt.FlushFinalBlock();
  1135. //将流转成byte[]
  1136. var encrypted = msEncrypt.ToArray();
  1137. if (encrypted.Length > 1024)
  1138. {
  1139. return;
  1140. }
  1141. //得到加密后数据的大小,将结果存在指定的位置。
  1142. index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
  1143. index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
  1144. //将加密后的结果写入index(覆盖)
  1145. for (int i = 0; i < encrypted.Length; i++)
  1146. {
  1147. index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
  1148. }
  1149. //建立文件流
  1150. using var newStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
  1151. newStream.Write(index, 0, 10261);
  1152. newStream.Flush();
  1153. newStream.Close();
  1154. }
  1155. #endregion
  1156. #region 从一个文件中解密出一段文本
  1157. /// <summary>
  1158. /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  1159. /// </summary>
  1160. /// <param name="filePath">要解密的文件</param>
  1161. /// <param name="dataIndex">要从哪一个块中解密</param>
  1162. /// <param name="iv">初始化向量</param>
  1163. /// <param name="key">解密密匙</param>
  1164. /// <returns>解密后的文本</returns>
  1165. public static string DecryptFromFile(this string filePath, int dataIndex, byte[] iv, byte[] key)
  1166. {
  1167. if ((dataIndex > 10) && (dataIndex < 1))
  1168. {
  1169. return "";
  1170. }
  1171. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1172. using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
  1173. var msDecrypt = new MemoryStream();
  1174. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  1175. var index = new byte[10261];
  1176. tmpFileStream.Read(index, 0, 10261);
  1177. var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
  1178. var tmp = new byte[count];
  1179. Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
  1180. csDecrypt.Write(tmp, 0, count);
  1181. csDecrypt.FlushFinalBlock();
  1182. var decrypted = msDecrypt.ToArray();
  1183. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  1184. }
  1185. #endregion
  1186. #region 将一段文本加密后保存到一个文件
  1187. /// <summary>
  1188. /// 将一段文本加密后保存到一个文件
  1189. /// </summary>
  1190. /// <param name="toEncryptText">要加密的文本数据</param>
  1191. /// <param name="filePath">要保存的文件</param>
  1192. /// <param name="iv">初始化向量</param>
  1193. /// <param name="key">加密密匙</param>
  1194. /// <returns>是否加密成功</returns>
  1195. public static void EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
  1196. {
  1197. using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
  1198. using var encryptor = _rc2Csp.CreateEncryptor(key, iv);
  1199. var msEncrypt = new MemoryStream();
  1200. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  1201. var tmp = _textConverter.GetBytes(toEncryptText);
  1202. csEncrypt.Write(tmp, 0, tmp.Length);
  1203. csEncrypt.FlushFinalBlock();
  1204. var encrypted = msEncrypt.ToArray();
  1205. tmpFileStream.Write(encrypted, 0, encrypted.Length);
  1206. tmpFileStream.Flush();
  1207. }
  1208. #endregion
  1209. #region 将一个被加密的文件解密
  1210. /// <summary>
  1211. /// 将一个被加密的文件解密
  1212. /// </summary>
  1213. /// <param name="filePath">要解密的文件</param>
  1214. /// <param name="iv">初始化向量</param>
  1215. /// <param name="key">解密密匙</param>
  1216. /// <returns>解密后的文本</returns>
  1217. public static string DecryptFromFile(this string filePath, byte[] iv, byte[] key)
  1218. {
  1219. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1220. using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
  1221. var msDecrypt = new MemoryStream();
  1222. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  1223. var tmp = new byte[tmpFileStream.Length];
  1224. tmpFileStream.Read(tmp, 0, tmp.Length);
  1225. csDecrypt.Write(tmp, 0, tmp.Length);
  1226. csDecrypt.FlushFinalBlock();
  1227. var decrypted = msDecrypt.ToArray();
  1228. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  1229. }
  1230. #endregion
  1231. #region 设置加密或解密的初始化向量
  1232. /// <summary>
  1233. /// 设置加密或解密的初始化向量
  1234. /// </summary>
  1235. /// <param name="s">长度等于8的ASCII字符集的字符串</param>
  1236. public static void SetIV(this string s)
  1237. {
  1238. if (s.Length != 8)
  1239. {
  1240. // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
  1241. _iv = null;
  1242. return;
  1243. }
  1244. try
  1245. {
  1246. _iv = _asciiEncoding.GetBytes(s);
  1247. }
  1248. catch (Exception)
  1249. {
  1250. // MessageBox.Show("输入的字符串必须为长度为8的且属于ASCII字符集的字符串");
  1251. _iv = null;
  1252. }
  1253. }
  1254. #endregion
  1255. #region 设置加密或解密的密匙
  1256. /// <summary>
  1257. /// 设置加密或解密的密匙
  1258. /// </summary>
  1259. /// <param name="s">长度等于16的ASCII字符集的字符串</param>
  1260. public static void SetKey(this string s)
  1261. {
  1262. if (s.Length != 16)
  1263. {
  1264. // MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
  1265. _key = null;
  1266. return;
  1267. }
  1268. try
  1269. {
  1270. _key = _asciiEncoding.GetBytes(s);
  1271. }
  1272. catch (Exception)
  1273. {
  1274. //MessageBox.Show("输入的字符串必须为长度为16的且属于ASCII字符集的字符串");
  1275. _key = null;
  1276. }
  1277. }
  1278. #endregion
  1279. }
  1280. /// <summary>
  1281. /// 对称加密解密算法类
  1282. /// </summary>
  1283. public static class Rijndael
  1284. {
  1285. private static string _key;
  1286. private static SymmetricAlgorithm _mobjCryptoService;
  1287. /// <summary>
  1288. /// 对称加密类的构造函数
  1289. /// </summary>
  1290. public static void SymmetricMethod()
  1291. {
  1292. _mobjCryptoService = new RijndaelManaged();
  1293. _key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
  1294. }
  1295. /// <summary>
  1296. /// 获得密钥
  1297. /// </summary>
  1298. /// <returns>密钥</returns>
  1299. private static byte[] GetLegalKey()
  1300. {
  1301. var sTemp = _key;
  1302. _mobjCryptoService.GenerateKey();
  1303. var bytTemp = _mobjCryptoService.Key;
  1304. var keyLength = bytTemp.Length;
  1305. if (sTemp.Length > keyLength)
  1306. sTemp = sTemp.Substring(0, keyLength);
  1307. else if (sTemp.Length < keyLength)
  1308. sTemp = sTemp.PadRight(keyLength, ' ');
  1309. return Encoding.ASCII.GetBytes(sTemp);
  1310. }
  1311. /// <summary>
  1312. /// 获得初始向量IV
  1313. /// </summary>
  1314. /// <returns>初试向量IV</returns>
  1315. private static byte[] GetLegalIV()
  1316. {
  1317. var sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUber57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
  1318. _mobjCryptoService.GenerateIV();
  1319. var bytTemp = _mobjCryptoService.IV;
  1320. var ivLength = bytTemp.Length;
  1321. if (sTemp.Length > ivLength)
  1322. sTemp = sTemp.Substring(0, ivLength);
  1323. else if (sTemp.Length < ivLength)
  1324. sTemp = sTemp.PadRight(ivLength, ' ');
  1325. return Encoding.ASCII.GetBytes(sTemp);
  1326. }
  1327. /// <summary>
  1328. /// 加密方法
  1329. /// </summary>
  1330. /// <param name="source">待加密的串</param>
  1331. /// <returns>经过加密的串</returns>
  1332. public static string Encrypto(this string source)
  1333. {
  1334. var bytIn = Encoding.UTF8.GetBytes(source);
  1335. var ms = new MemoryStream();
  1336. _mobjCryptoService.Key = GetLegalKey();
  1337. _mobjCryptoService.IV = GetLegalIV();
  1338. var encrypto = _mobjCryptoService.CreateEncryptor();
  1339. var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
  1340. cs.Write(bytIn, 0, bytIn.Length);
  1341. cs.FlushFinalBlock();
  1342. ms.Close();
  1343. var bytOut = ms.ToArray();
  1344. return Convert.ToBase64String(bytOut);
  1345. }
  1346. /// <summary>
  1347. /// 解密方法
  1348. /// </summary>
  1349. /// <param name="source">待解密的串</param>
  1350. /// <returns>经过解密的串</returns>
  1351. public static string Decrypto(this string source)
  1352. {
  1353. var bytIn = Convert.FromBase64String(source);
  1354. var ms = new MemoryStream(bytIn, 0, bytIn.Length);
  1355. _mobjCryptoService.Key = GetLegalKey();
  1356. _mobjCryptoService.IV = GetLegalIV();
  1357. var encrypto = _mobjCryptoService.CreateDecryptor();
  1358. var cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
  1359. var sr = new StreamReader(cs);
  1360. return sr.ReadToEnd();
  1361. }
  1362. }
  1363. }