Encrypt.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185
  1. using Masuit.Tools.Systems;
  2. using System;
  3. using System.IO;
  4. using System.Security.Cryptography;
  5. using System.Text;
  6. using System.Text.RegularExpressions;
  7. namespace Masuit.Tools.Security
  8. {
  9. /// <summary>
  10. /// 常用的加密解密算法
  11. /// </summary>
  12. public static class Encrypt
  13. {
  14. #region DES对称加密解密
  15. /// <summary>
  16. /// 加密字符串
  17. /// 加密密钥必须为8位
  18. /// </summary>
  19. /// <param name="strText">被加密的字符串</param>
  20. /// <param name="strEncrKey">8位长度密钥</param>
  21. /// <returns>加密后的数据</returns>
  22. public static string DesEncrypt(this string strText, string strEncrKey)
  23. {
  24. if (strEncrKey.Length < 8)
  25. {
  26. throw new Exception("密钥长度无效,密钥必须是8位!");
  27. }
  28. StringBuilder ret = new StringBuilder();
  29. using var des = DES.Create();
  30. byte[] inputByteArray = Encoding.Default.GetBytes(strText);
  31. des.Key = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
  32. des.IV = Encoding.ASCII.GetBytes(strEncrKey.Substring(0, 8));
  33. using var ms = new PooledMemoryStream();
  34. using var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  35. cs.Write(inputByteArray, 0, inputByteArray.Length);
  36. cs.FlushFinalBlock();
  37. foreach (byte b in ms.ToArray())
  38. {
  39. ret.AppendFormat($"{b:X2}");
  40. }
  41. return ret.ToString();
  42. }
  43. /// <summary>
  44. /// 加密字符串
  45. /// 加密密钥必须为8位
  46. /// </summary>
  47. /// <param name="strText">被加密的字符串</param>
  48. /// <param name="desKey"></param>
  49. /// <param name="desIV"></param>
  50. /// <returns>加密后的数据</returns>
  51. public static string DesEncrypt(this string strText, byte[] desKey, byte[] desIV)
  52. {
  53. StringBuilder ret = new StringBuilder();
  54. using var des = DES.Create();
  55. byte[] inputByteArray = Encoding.Default.GetBytes(strText);
  56. des.Key = desKey;
  57. des.IV = desIV;
  58. using var ms = new PooledMemoryStream();
  59. using var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
  60. cs.Write(inputByteArray, 0, inputByteArray.Length);
  61. cs.FlushFinalBlock();
  62. foreach (byte b in ms.ToArray())
  63. {
  64. ret.AppendFormat($"{b:X2}");
  65. }
  66. return ret.ToString();
  67. }
  68. /// <summary>
  69. /// DES加密文件
  70. /// </summary>
  71. /// <param name="fin">文件输入流</param>
  72. /// <param name="outFilePath">文件输出路径</param>
  73. /// <param name="strEncrKey">加密密钥</param>
  74. public static void DesEncrypt(this FileStream fin, string outFilePath, string strEncrKey)
  75. {
  76. byte[] iv =
  77. {
  78. 0x12,
  79. 0x34,
  80. 0x56,
  81. 0x78,
  82. 0x90,
  83. 0xAB,
  84. 0xCD,
  85. 0xEF
  86. };
  87. var byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
  88. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  89. fout.SetLength(0);
  90. byte[] bin = new byte[100];
  91. long rdlen = 0;
  92. long totlen = fin.Length;
  93. using var des = DES.Create();
  94. var encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, iv), CryptoStreamMode.Write);
  95. while (rdlen < totlen)
  96. {
  97. var len = fin.Read(bin, 0, 100);
  98. encStream.Write(bin, 0, len);
  99. rdlen += len;
  100. }
  101. }
  102. /// <summary>
  103. /// DES加密文件
  104. /// </summary>
  105. /// <param name="fin">文件输入流</param>
  106. /// <param name="outFilePath">文件输出路径</param>
  107. /// <param name="desKey"></param>
  108. /// <param name="desIV"></param>
  109. public static void DesEncrypt(this FileStream fin, string outFilePath, byte[] desKey, byte[] desIV)
  110. {
  111. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  112. fout.SetLength(0);
  113. byte[] bin = new byte[100];
  114. long rdlen = 0;
  115. long totlen = fin.Length;
  116. using var des = DES.Create();
  117. var encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
  118. while (rdlen < totlen)
  119. {
  120. var len = fin.Read(bin, 0, 100);
  121. encStream.Write(bin, 0, len);
  122. rdlen += len;
  123. }
  124. }
  125. /// <summary>
  126. /// DES解密文件
  127. /// </summary>
  128. /// <param name="fin">输入文件流</param>
  129. /// <param name="outFilePath">文件输出路径</param>
  130. /// <param name="sDecrKey">解密密钥</param>
  131. public static void DesDecrypt(this FileStream fin, string outFilePath, string sDecrKey)
  132. {
  133. byte[] iv =
  134. {
  135. 0x12,
  136. 0x34,
  137. 0x56,
  138. 0x78,
  139. 0x90,
  140. 0xAB,
  141. 0xCD,
  142. 0xEF
  143. };
  144. var byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
  145. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  146. fout.SetLength(0);
  147. byte[] bin = new byte[100];
  148. long rdlen = 0;
  149. long totlen = fin.Length;
  150. using var des = DES.Create();
  151. var encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, iv), CryptoStreamMode.Write);
  152. while (rdlen < totlen)
  153. {
  154. var len = fin.Read(bin, 0, 100);
  155. encStream.Write(bin, 0, len);
  156. rdlen += len;
  157. }
  158. }
  159. /// <summary>
  160. /// DES解密文件
  161. /// </summary>
  162. /// <param name="fin">输入文件流</param>
  163. /// <param name="outFilePath">文件输出路径</param>
  164. /// <param name="desKey"></param>
  165. /// <param name="desIV"></param>
  166. public static void DesDecrypt(this FileStream fin, string outFilePath, byte[] desKey, byte[] desIV)
  167. {
  168. using var fout = new FileStream(outFilePath, FileMode.OpenOrCreate, FileAccess.Write);
  169. fout.SetLength(0);
  170. byte[] bin = new byte[100];
  171. long rdlen = 0;
  172. long totlen = fin.Length;
  173. using var des = DES.Create();
  174. var encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
  175. while (rdlen < totlen)
  176. {
  177. var len = fin.Read(bin, 0, 100);
  178. encStream.Write(bin, 0, len);
  179. rdlen += len;
  180. }
  181. }
  182. /// <summary>
  183. /// DES解密算法
  184. /// 密钥为8位
  185. /// </summary>
  186. /// <param name="pToDecrypt">需要解密的字符串</param>
  187. /// <param name="sKey">密钥</param>
  188. /// <returns>解密后的数据</returns>
  189. public static string DesDecrypt(this string pToDecrypt, string sKey)
  190. {
  191. if (sKey.Length < 8)
  192. {
  193. throw new Exception("密钥长度无效,密钥必须是8位!");
  194. }
  195. using var ms = new PooledMemoryStream();
  196. using var des = DES.Create();
  197. var inputByteArray = new byte[pToDecrypt.Length / 2];
  198. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  199. {
  200. int i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
  201. inputByteArray[x] = (byte)i;
  202. }
  203. des.Key = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
  204. des.IV = Encoding.ASCII.GetBytes(sKey.Substring(0, 8));
  205. using var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  206. cs.Write(inputByteArray, 0, inputByteArray.Length);
  207. cs.FlushFinalBlock();
  208. return Encoding.Default.GetString(ms.ToArray());
  209. }
  210. /// <summary>
  211. /// DES解密算法
  212. /// 密钥为8位
  213. /// </summary>
  214. /// <param name="pToDecrypt">需要解密的字符串</param>
  215. /// <param name="desKey"></param>
  216. /// <param name="desIV"></param>
  217. /// <returns>解密后的数据</returns>
  218. public static string DesDecrypt(this string pToDecrypt, byte[] desKey, byte[] desIV)
  219. {
  220. using var ms = new PooledMemoryStream();
  221. using var des = DES.Create();
  222. var inputByteArray = new byte[pToDecrypt.Length / 2];
  223. for (int x = 0; x < pToDecrypt.Length / 2; x++)
  224. {
  225. int i = Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16);
  226. inputByteArray[x] = (byte)i;
  227. }
  228. des.Key = desKey;
  229. des.IV = desIV;
  230. using var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
  231. cs.Write(inputByteArray, 0, inputByteArray.Length);
  232. cs.FlushFinalBlock();
  233. return Encoding.Default.GetString(ms.ToArray());
  234. }
  235. #endregion
  236. #region 对称加密算法AES加密解密
  237. private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79, 0x53, 0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
  238. /// <summary>
  239. /// 生成符合AES加密规则的密钥
  240. /// </summary>
  241. /// <param name="length"></param>
  242. /// <returns></returns>
  243. public static string GenerateAesKey(int length)
  244. {
  245. using var aes = Aes.Create();
  246. aes.KeySize = length;
  247. aes.BlockSize = 128;
  248. aes.GenerateKey();
  249. return Convert.ToBase64String(aes.Key);
  250. }
  251. /// <summary>
  252. /// 对称加密算法AES(块式加密算法)
  253. /// </summary>
  254. /// <param name="encryptString">待加密字符串</param>
  255. /// <param name="encryptKey">加密密钥,须半角字符</param>
  256. /// <param name="mode">加密模式</param>
  257. /// <returns>加密结果字符串</returns>
  258. public static string AESEncrypt(this string encryptString, string encryptKey, CipherMode mode = CipherMode.CBC)
  259. {
  260. encryptKey = GetSubString(encryptKey, 32, "");
  261. encryptKey = encryptKey.PadRight(32, ' ');
  262. using var aes = Aes.Create("AesManaged");
  263. aes.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
  264. aes.IV = Keys;
  265. aes.Mode = mode;
  266. using ICryptoTransform rijndaelEncrypt = aes.CreateEncryptor();
  267. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  268. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  269. return Convert.ToBase64String(encryptedData);
  270. }
  271. /// <summary>
  272. /// 对称加密算法AES加密(块式加密算法)
  273. /// </summary>
  274. /// <param name="encryptString">待加密字符串</param>
  275. /// <param name="options">加密选项</param>
  276. /// <returns>加密结果字符串</returns>
  277. public static string AESEncrypt(this string encryptString, Aes options)
  278. {
  279. using ICryptoTransform rijndaelEncrypt = options.CreateEncryptor();
  280. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  281. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  282. return Convert.ToBase64String(encryptedData);
  283. }
  284. /// <summary>
  285. /// 对称加密算法AES加密(块式加密算法)
  286. /// </summary>
  287. /// <param name="encryptString">待加密字符串</param>
  288. /// <param name="encryptKey">加密密钥,须半角字符</param>
  289. /// <param name="mode">加密模式</param>
  290. /// <returns>加密结果字符串</returns>
  291. public static string AESEncrypt(this string encryptString, byte[] encryptKey, CipherMode mode = CipherMode.CBC)
  292. {
  293. using var aes = Aes.Create("AesManaged");
  294. aes.Key = encryptKey;
  295. aes.IV = Keys;
  296. aes.Mode = mode;
  297. using ICryptoTransform rijndaelEncrypt = aes.CreateEncryptor();
  298. byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
  299. byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  300. return Convert.ToBase64String(encryptedData);
  301. }
  302. /// <summary>
  303. /// 对称加密算法AES解密字符串
  304. /// </summary>
  305. /// <param name="decryptString">待解密的字符串</param>
  306. /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
  307. /// <param name="mode">加密模式</param>
  308. /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
  309. public static string AESDecrypt(this string decryptString, string decryptKey, CipherMode mode = CipherMode.CBC)
  310. {
  311. try
  312. {
  313. decryptKey = GetSubString(decryptKey, 32, "");
  314. decryptKey = decryptKey.PadRight(32, ' ');
  315. using var aes = Aes.Create("AesManaged");
  316. aes.Key = Encoding.UTF8.GetBytes(decryptKey);
  317. aes.IV = Keys;
  318. aes.Mode = mode;
  319. using ICryptoTransform rijndaelDecrypt = aes.CreateDecryptor();
  320. byte[] inputData = Convert.FromBase64String(decryptString);
  321. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  322. return Encoding.UTF8.GetString(decryptedData);
  323. }
  324. catch
  325. {
  326. return string.Empty;
  327. }
  328. }
  329. /// <summary>
  330. /// 对称加密算法AES解密字符串
  331. /// </summary>
  332. /// <param name="decryptString">待解密的字符串</param>
  333. /// <param name="options">加密选项</param>
  334. /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
  335. public static string AESDecrypt(this string decryptString, Aes options)
  336. {
  337. try
  338. {
  339. using ICryptoTransform rijndaelDecrypt = options.CreateDecryptor();
  340. byte[] inputData = Convert.FromBase64String(decryptString);
  341. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  342. return Encoding.UTF8.GetString(decryptedData);
  343. }
  344. catch
  345. {
  346. return string.Empty;
  347. }
  348. }
  349. /// <summary>
  350. /// 对称加密算法AES解密字符串
  351. /// </summary>
  352. /// <param name="decryptString">待解密的字符串</param>
  353. /// <param name="decryptKey">解密密钥,和加密密钥相同</param>
  354. /// <param name="mode">加密模式</param>
  355. /// <returns>解密成功返回解密后的字符串,失败返回空</returns>
  356. public static string AESDecrypt(this string decryptString, byte[] decryptKey, CipherMode mode = CipherMode.CBC)
  357. {
  358. try
  359. {
  360. using var aes = Aes.Create("AesManaged");
  361. aes.Key = decryptKey;
  362. aes.IV = Keys;
  363. aes.Mode = mode;
  364. using ICryptoTransform rijndaelDecrypt = aes.CreateDecryptor();
  365. byte[] inputData = Convert.FromBase64String(decryptString);
  366. byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
  367. return Encoding.UTF8.GetString(decryptedData);
  368. }
  369. catch
  370. {
  371. return string.Empty;
  372. }
  373. }
  374. /// <summary>
  375. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  376. /// </summary>
  377. /// <param name="sourceString">源字符串</param>
  378. /// <param name="length">所取字符串字节长度</param>
  379. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  380. /// <returns>某字符串的一部分</returns>
  381. private static string GetSubString(this string sourceString, int length, string tailString)
  382. {
  383. return GetSubString(sourceString, 0, length, tailString);
  384. }
  385. /// <summary>
  386. /// 按字节长度(按字节,一个汉字为2个字节)取得某字符串的一部分
  387. /// </summary>
  388. /// <param name="sourceString">源字符串</param>
  389. /// <param name="startIndex">索引位置,以0开始</param>
  390. /// <param name="length">所取字符串字节长度</param>
  391. /// <param name="tailString">附加字符串(当字符串不够长时,尾部所添加的字符串,一般为"...")</param>
  392. /// <returns>某字符串的一部分</returns>
  393. private static string GetSubString(this string sourceString, int startIndex, int length, string tailString)
  394. {
  395. //当是日文或韩文时(注:中文的范围:\u4e00 - \u9fa5, 日文在\u0800 - \u4e00, 韩文为\xAC00-\xD7A3)
  396. if (Regex.IsMatch(sourceString, "[\u0800-\u4e00]+") || Regex.IsMatch(sourceString, "[\xAC00-\xD7A3]+"))
  397. {
  398. //当截取的起始位置超出字段串长度时
  399. if (startIndex >= sourceString.Length)
  400. {
  401. return string.Empty;
  402. }
  403. return sourceString.Substring(startIndex, length + startIndex > sourceString.Length ? (sourceString.Length - startIndex) : length);
  404. }
  405. //中文字符,如"中国人民abcd123"
  406. if (length <= 0)
  407. {
  408. return string.Empty;
  409. }
  410. byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
  411. //当字符串长度大于起始位置
  412. if (bytesSource.Length > startIndex)
  413. {
  414. int endIndex = bytesSource.Length;
  415. //当要截取的长度在字符串的有效长度范围内
  416. if (bytesSource.Length > (startIndex + length))
  417. {
  418. endIndex = length + startIndex;
  419. }
  420. else
  421. {
  422. //当不在有效范围内时,只取到字符串的结尾
  423. length = bytesSource.Length - startIndex;
  424. tailString = "";
  425. }
  426. var anResultFlag = new int[length];
  427. int nFlag = 0;
  428. //字节大于127为双字节字符
  429. for (int i = startIndex; i < endIndex; i++)
  430. {
  431. if (bytesSource[i] > 127)
  432. {
  433. nFlag++;
  434. if (nFlag == 3)
  435. {
  436. nFlag = 1;
  437. }
  438. }
  439. else
  440. {
  441. nFlag = 0;
  442. }
  443. anResultFlag[i] = nFlag;
  444. }
  445. //最后一个字节为双字节字符的一半
  446. if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
  447. {
  448. length++;
  449. }
  450. byte[] bsResult = new byte[length];
  451. Array.Copy(bytesSource, startIndex, bsResult, 0, length);
  452. var myResult = Encoding.Default.GetString(bsResult);
  453. myResult += tailString;
  454. return myResult;
  455. }
  456. return string.Empty;
  457. }
  458. /// <summary>
  459. /// 加密文件流
  460. /// </summary>
  461. /// <param name="fs">需要加密的文件流</param>
  462. /// <param name="decryptKey">加密密钥</param>
  463. /// <param name="mode">加密模式</param>
  464. /// <returns>加密流</returns>
  465. public static CryptoStream AESEncryptStrream(this FileStream fs, string decryptKey, CipherMode mode = CipherMode.CBC)
  466. {
  467. decryptKey = GetSubString(decryptKey, 32, "");
  468. decryptKey = decryptKey.PadRight(32, ' ');
  469. using var aes = Aes.Create("AesManaged");
  470. aes.Key = Encoding.UTF8.GetBytes(decryptKey);
  471. aes.IV = Keys;
  472. aes.Mode = mode;
  473. using var encrypto = aes.CreateEncryptor();
  474. return new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
  475. }
  476. /// <summary>
  477. /// 加密文件流
  478. /// </summary>
  479. /// <param name="fs">需要加密的文件流</param>
  480. /// <param name="decryptKey">加密密钥</param>
  481. /// <param name="mode">加密模式</param>
  482. /// <returns>加密流</returns>
  483. public static CryptoStream AESEncryptStrream(this FileStream fs, byte[] decryptKey, CipherMode mode = CipherMode.CBC)
  484. {
  485. using var aes = Aes.Create("AesManaged");
  486. aes.Key = decryptKey;
  487. aes.IV = Keys;
  488. aes.Mode = mode;
  489. using var encrypto = aes.CreateEncryptor();
  490. return new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
  491. }
  492. /// <summary>
  493. /// 解密文件流
  494. /// </summary>
  495. /// <param name="fs">需要解密的文件流</param>
  496. /// <param name="decryptKey">解密密钥</param>
  497. /// <param name="mode">加密模式</param>
  498. /// <returns>加密流</returns>
  499. public static CryptoStream AESDecryptStream(this FileStream fs, string decryptKey, CipherMode mode = CipherMode.CBC)
  500. {
  501. decryptKey = GetSubString(decryptKey, 32, "");
  502. decryptKey = decryptKey.PadRight(32, ' ');
  503. using var aes = Aes.Create("AesManaged");
  504. aes.Key = Encoding.UTF8.GetBytes(decryptKey);
  505. aes.IV = Keys;
  506. aes.Mode = mode;
  507. using var decrypto = aes.CreateDecryptor();
  508. return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
  509. }
  510. /// <summary>
  511. /// 解密文件流
  512. /// </summary>
  513. /// <param name="fs">需要解密的文件流</param>
  514. /// <param name="decryptKey">解密密钥</param>
  515. /// <param name="mode">加密模式</param>
  516. /// <returns>加密流</returns>
  517. public static CryptoStream AESDecryptStream(this FileStream fs, byte[] decryptKey, CipherMode mode = CipherMode.CBC)
  518. {
  519. using var aes = Aes.Create("AesManaged");
  520. aes.Key = decryptKey;
  521. aes.IV = Keys;
  522. aes.Mode = mode;
  523. using var decrypto = aes.CreateDecryptor();
  524. return new CryptoStream(fs, decrypto, CryptoStreamMode.Read);
  525. }
  526. /// <summary>
  527. /// 对指定文件AES加密
  528. /// </summary>
  529. /// <param name="input">源文件流</param>
  530. /// <param name="key">加密密钥</param>
  531. /// <param name="mode">加密模式</param>
  532. /// <param name="outputPath">输出文件路径</param>
  533. public static void AESEncryptFile(this FileStream input, string outputPath, string key, CipherMode mode = CipherMode.CBC)
  534. {
  535. using var fren = new FileStream(outputPath, FileMode.Create);
  536. using var enfr = AESEncryptStrream(fren, key, mode);
  537. byte[] bytearrayinput = new byte[input.Length];
  538. _ = input.Read(bytearrayinput, 0, bytearrayinput.Length);
  539. enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
  540. }
  541. /// <summary>
  542. /// 对指定的文件AES解密
  543. /// </summary>
  544. /// <param name="input">源文件流</param>
  545. /// <param name="key">解密密钥</param>
  546. /// <param name="mode">加密模式</param>
  547. /// <param name="outputPath">输出文件路径</param>
  548. public static void AESDecryptFile(this FileStream input, string outputPath, string key, CipherMode mode = CipherMode.CBC)
  549. {
  550. using FileStream frde = new FileStream(outputPath, FileMode.Create);
  551. using CryptoStream defr = AESDecryptStream(input, key, mode);
  552. byte[] bytearrayoutput = new byte[1024];
  553. while (true)
  554. {
  555. var count = defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
  556. frde.Write(bytearrayoutput, 0, count);
  557. if (count < bytearrayoutput.Length)
  558. {
  559. break;
  560. }
  561. }
  562. }
  563. #endregion
  564. #region Base64加密解密
  565. /// <summary>
  566. /// Base64加密
  567. /// </summary>
  568. /// <param name="str">需要加密的字符串</param>
  569. /// <returns>加密后的数据</returns>
  570. public static string Base64Encrypt(this string str)
  571. {
  572. byte[] encbuff = Encoding.UTF8.GetBytes(str);
  573. return Convert.ToBase64String(encbuff);
  574. }
  575. /// <summary>
  576. /// Base64解密
  577. /// </summary>
  578. /// <param name="str">需要解密的字符串</param>
  579. /// <returns>解密后的数据</returns>
  580. public static string Base64Decrypt(this string str)
  581. {
  582. try
  583. {
  584. byte[] decbuff = Convert.FromBase64String(str);
  585. return Encoding.UTF8.GetString(decbuff);
  586. }
  587. catch
  588. {
  589. return str;
  590. }
  591. }
  592. #endregion
  593. /// <summary>
  594. /// SHA256函数
  595. /// </summary>
  596. /// <param name="str">原始字符串</param>
  597. /// <returns>SHA256结果(返回长度为44字节的字符串)</returns>
  598. public static string SHA256(this string str)
  599. {
  600. byte[] sha256Data = Encoding.UTF8.GetBytes(str);
  601. using var sha256 = System.Security.Cryptography.SHA256.Create();
  602. byte[] result = sha256.ComputeHash(sha256Data);
  603. return Convert.ToBase64String(result); //返回长度为44字节的字符串
  604. }
  605. #region MD5摘要算法
  606. #region 对字符串进行MD5摘要
  607. /// <summary>
  608. /// 对字符串进行MD5摘要
  609. /// </summary>
  610. /// <param name="message">需要摘要的字符串</param>
  611. /// <returns>MD5摘要字符串</returns>
  612. public static string MDString(this string message)
  613. {
  614. MD5 md5 = MD5.Create();
  615. byte[] buffer = Encoding.Default.GetBytes(message);
  616. byte[] bytes = md5.ComputeHash(buffer);
  617. return GetHexString(bytes);
  618. }
  619. /// <summary>
  620. /// 对字符串进行MD5二次摘要
  621. /// </summary>
  622. /// <param name="message">需要摘要的字符串</param>
  623. /// <returns>MD5摘要字符串</returns>
  624. public static string MDString2(this string message) => MDString(MDString(message));
  625. /// <summary>
  626. /// MD5 三次摘要算法
  627. /// </summary>
  628. /// <param name="s">需要摘要的字符串</param>
  629. /// <returns>MD5摘要字符串</returns>
  630. public static string MDString3(this string s)
  631. {
  632. using MD5 md5 = MD5.Create();
  633. byte[] bytes = Encoding.ASCII.GetBytes(s);
  634. byte[] bytes1 = md5.ComputeHash(bytes);
  635. byte[] bytes2 = md5.ComputeHash(bytes1);
  636. byte[] bytes3 = md5.ComputeHash(bytes2);
  637. return GetHexString(bytes3);
  638. }
  639. /// <summary>
  640. /// 对字符串进行MD5加盐摘要
  641. /// </summary>
  642. /// <param name="message">需要摘要的字符串</param>
  643. /// <param name="salt">盐</param>
  644. /// <returns>MD5摘要字符串</returns>
  645. public static string MDString(this string message, string salt) => MDString(message + salt);
  646. /// <summary>
  647. /// 对字符串进行MD5二次加盐摘要
  648. /// </summary>
  649. /// <param name="message">需要摘要的字符串</param>
  650. /// <param name="salt">盐</param>
  651. /// <returns>MD5摘要字符串</returns>
  652. public static string MDString2(this string message, string salt) => MDString(MDString(message + salt), salt);
  653. /// <summary>
  654. /// MD5 三次摘要算法
  655. /// </summary>
  656. /// <param name="s">需要摘要的字符串</param>
  657. /// <param name="salt">盐</param>
  658. /// <returns>MD5摘要字符串</returns>
  659. public static string MDString3(this string s, string salt)
  660. {
  661. using MD5 md5 = MD5.Create();
  662. byte[] bytes = Encoding.ASCII.GetBytes(s + salt);
  663. byte[] bytes1 = md5.ComputeHash(bytes);
  664. byte[] bytes2 = md5.ComputeHash(bytes1);
  665. byte[] bytes3 = md5.ComputeHash(bytes2);
  666. return GetHexString(bytes3);
  667. }
  668. #endregion
  669. #region 获取文件的MD5值
  670. /// <summary>
  671. /// 获取文件的MD5值
  672. /// </summary>
  673. /// <param name="fileName">需要求MD5值的文件的文件名及路径</param>
  674. /// <returns>MD5摘要字符串</returns>
  675. public static string MDFile(this string fileName)
  676. {
  677. using var fs = new BufferedStream(File.Open(fileName, FileMode.Open, FileAccess.Read), 1048576);
  678. using MD5 md5 = MD5.Create();
  679. byte[] bytes = md5.ComputeHash(fs);
  680. return GetHexString(bytes);
  681. }
  682. /// <summary>
  683. /// 计算文件的sha256
  684. /// </summary>
  685. /// <param name="stream"></param>
  686. /// <returns></returns>
  687. public static string SHA256(this Stream stream)
  688. {
  689. using var fs = new BufferedStream(stream, 1048576);
  690. using var sha = System.Security.Cryptography.SHA256.Create();
  691. byte[] checksum = sha.ComputeHash(fs);
  692. return BitConverter.ToString(checksum).Replace("-", string.Empty);
  693. }
  694. /// <summary>
  695. /// 获取数据流的MD5摘要值
  696. /// </summary>
  697. /// <param name="stream"></param>
  698. /// <returns>MD5摘要字符串</returns>
  699. public static string MDString(this Stream stream)
  700. {
  701. using var fs = new BufferedStream(stream, 1048576);
  702. using MD5 md5 = MD5.Create();
  703. byte[] bytes = md5.ComputeHash(fs);
  704. var mdstr = GetHexString(bytes);
  705. stream.Position = 0;
  706. return mdstr;
  707. }
  708. public static string GetHexString(byte[] bytes)
  709. {
  710. var hexArray = new char[bytes.Length << 1];
  711. for (var i = 0; i < hexArray.Length; i += 2)
  712. {
  713. var b = bytes[i >> 1];
  714. hexArray[i] = GetHexValue(b >> 4); // b / 16
  715. hexArray[i + 1] = GetHexValue(b & 0xF); // b % 16
  716. }
  717. return new string(hexArray, 0, hexArray.Length);
  718. static char GetHexValue(int i)
  719. {
  720. if (i < 10)
  721. {
  722. return (char)(i + '0');
  723. }
  724. return (char)(i - 10 + 'a');
  725. }
  726. }
  727. #endregion
  728. #endregion MD5摘要算法
  729. }
  730. /// <summary>
  731. /// RC2加密解密算法
  732. /// </summary>
  733. public static class RC2Crypt
  734. {
  735. private static ASCIIEncoding _asciiEncoding;
  736. private static byte[] _iv;
  737. private static byte[] _key;
  738. private static RC2 _rc2Csp;
  739. private static UnicodeEncoding _textConverter;
  740. static RC2Crypt()
  741. {
  742. InitializeComponent();
  743. }
  744. private static void InitializeComponent()
  745. {
  746. _key = new byte[]
  747. {
  748. 106,
  749. 51,
  750. 25,
  751. 141,
  752. 157,
  753. 142,
  754. 23,
  755. 111,
  756. 234,
  757. 159,
  758. 187,
  759. 154,
  760. 215,
  761. 34,
  762. 37,
  763. 204
  764. };
  765. _iv = new byte[]
  766. {
  767. 135,
  768. 186,
  769. 133,
  770. 136,
  771. 184,
  772. 149,
  773. 153,
  774. 144
  775. };
  776. _asciiEncoding = new ASCIIEncoding();
  777. _textConverter = new UnicodeEncoding();
  778. _rc2Csp = RC2.Create();
  779. }
  780. #region 将文本数据加密后写入一个文件
  781. /// <summary>
  782. /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
  783. /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
  784. /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
  785. /// </summary>
  786. /// <param name="toEncryptText">要加密的文本数据</param>
  787. /// <param name="filePath">要写入的文件</param>
  788. /// <param name="dataIndex">写入第几块,取值为1--10</param>
  789. /// <returns>是否操作成功</returns>
  790. public static bool EncryptToFile(this string toEncryptText, string filePath, int dataIndex)
  791. {
  792. var r = false;
  793. if ((dataIndex > 10) && (dataIndex < 1))
  794. {
  795. return r;
  796. }
  797. //打开要写入的文件,主要是为了保持原文件的内容不丢失
  798. var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  799. var index = new byte[10261];
  800. //将读取的内容写到byte数组
  801. tmpFileStream.Read(index, 0, 10261);
  802. tmpFileStream.Close();
  803. //定义基本的加密转换运算
  804. using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
  805. using var msEncrypt = new PooledMemoryStream();
  806. //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
  807. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  808. //将要加密的文本转换成UTF-16 编码,保存在tmp数组。
  809. var tmp = _textConverter.GetBytes(toEncryptText);
  810. //将tmp输入csEncrypt,将通过Encryptor来加密。
  811. csEncrypt.Write(tmp, 0, tmp.Length);
  812. //输出到msEnctypt
  813. csEncrypt.FlushFinalBlock();
  814. //将流转成byte[]
  815. var encrypted = msEncrypt.ToArray();
  816. if (encrypted.Length > 1024)
  817. return false;
  818. //得到加密后数据的大小,将结果存在指定的位置。
  819. index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
  820. index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
  821. //将加密后的结果写入index(覆盖)
  822. for (var i = 0; i < encrypted.Length; i++)
  823. index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
  824. //建立文件流
  825. tmpFileStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
  826. //写文件
  827. tmpFileStream.Write(index, 0, 10261);
  828. tmpFileStream.Flush();
  829. r = true;
  830. tmpFileStream.Close();
  831. return r;
  832. }
  833. #endregion
  834. #region 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  835. /// <summary>
  836. /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  837. /// </summary>
  838. /// <param name="filePath">要解密的文件</param>
  839. /// <param name="dataIndex">要从哪一个块中解密</param>
  840. /// <returns>解密后的文本</returns>
  841. public static string DecryptFromFile(this string filePath, int dataIndex)
  842. {
  843. if (dataIndex > 10 && dataIndex < 1)
  844. {
  845. return "";
  846. }
  847. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  848. using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
  849. using var msDecrypt = new PooledMemoryStream();
  850. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  851. var index = new byte[10261];
  852. tmpFileStream.Read(index, 0, 10261);
  853. var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
  854. var tmp = new byte[count];
  855. Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
  856. csDecrypt.Write(tmp, 0, count);
  857. csDecrypt.FlushFinalBlock();
  858. var decrypted = msDecrypt.ToArray();
  859. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  860. }
  861. #endregion
  862. #region 将一段文本加密后保存到一个文件
  863. /// <summary>
  864. /// 将一段文本加密后保存到一个文件
  865. /// </summary>
  866. /// <param name="toEncryptText">要加密的文本数据</param>
  867. /// <param name="filePath">要保存的文件</param>
  868. /// <returns>是否加密成功</returns>
  869. public static void EncryptToFile(this string toEncryptText, string filePath)
  870. {
  871. using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
  872. using var encryptor = _rc2Csp.CreateEncryptor(_key, _iv);
  873. using var msEncrypt = new PooledMemoryStream();
  874. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  875. var tmp = _textConverter.GetBytes(toEncryptText);
  876. csEncrypt.Write(tmp, 0, tmp.Length);
  877. csEncrypt.FlushFinalBlock();
  878. var encrypted = msEncrypt.ToArray();
  879. tmpFileStream.Write(encrypted, 0, encrypted.Length);
  880. }
  881. #endregion
  882. #region 将一个被加密的文件解密
  883. /// <summary>
  884. /// 将一个被加密的文件解密
  885. /// </summary>
  886. /// <param name="filePath">要解密的文件</param>
  887. /// <returns>解密后的文本</returns>
  888. public static string DecryptFromFile(this string filePath)
  889. {
  890. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  891. using var decryptor = _rc2Csp.CreateDecryptor(_key, _iv);
  892. using var msDecrypt = new PooledMemoryStream();
  893. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  894. var tmp = new byte[tmpFileStream.Length];
  895. tmpFileStream.Read(tmp, 0, tmp.Length);
  896. csDecrypt.Write(tmp, 0, tmp.Length);
  897. csDecrypt.FlushFinalBlock();
  898. var decrypted = msDecrypt.ToArray();
  899. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  900. }
  901. #endregion
  902. #region 将文本数据加密后写入一个文件
  903. /// <summary>
  904. /// 将文本数据加密后写入一个文件,其中,这个文件是用InitBinFile建立的,这个文件将被分成十块,
  905. /// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
  906. /// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
  907. /// </summary>
  908. /// <param name="toEncryptText">要加密的文本数据</param>
  909. /// <param name="filePath">要写入的文件</param>
  910. /// <param name="dataIndex">写入第几块,取值为1--10</param>
  911. /// <param name="IV">初始化向量</param>
  912. /// <param name="Key">加密密匙</param>
  913. /// <returns>是否操作成功</returns>
  914. public static void EncryptToFile(this string toEncryptText, string filePath, int dataIndex, byte[] IV, byte[] Key)
  915. {
  916. if ((dataIndex > 10) && (dataIndex < 1))
  917. {
  918. return;
  919. }
  920. //打开要写入的文件,主要是为了保持原文件的内容不丢失
  921. using var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  922. var index = new byte[10261];
  923. //将读取的内容写到byte数组
  924. fs.Read(index, 0, 10261);
  925. //定义基本的加密转换运算
  926. using var encryptor = _rc2Csp.CreateEncryptor(Key, IV);
  927. using var msEncrypt = new PooledMemoryStream();
  928. //在此加密转换流中,加密将从csEncrypt,加密后,结果在msEncrypt流中。
  929. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  930. var tmp = _textConverter.GetBytes(toEncryptText);
  931. //将tmp输入csEncrypt,将通过Encryptor来加密。
  932. csEncrypt.Write(tmp, 0, tmp.Length);
  933. //输出到msEnctypt
  934. csEncrypt.FlushFinalBlock();
  935. //将流转成byte[]
  936. var encrypted = msEncrypt.ToArray();
  937. if (encrypted.Length > 1024)
  938. {
  939. return;
  940. }
  941. //得到加密后数据的大小,将结果存在指定的位置。
  942. index[dataIndex * 2 - 1] = Convert.ToByte(Convert.ToString(encrypted.Length / 128));
  943. index[dataIndex * 2] = Convert.ToByte(Convert.ToString(encrypted.Length % 128));
  944. //将加密后的结果写入index(覆盖)
  945. for (int i = 0; i < encrypted.Length; i++)
  946. {
  947. index[1024 * (dataIndex - 1) + 21 + i] = encrypted[i];
  948. }
  949. //建立文件流
  950. using var newStream = new FileStream(filePath, FileMode.Truncate, FileAccess.Write, FileShare.None, 1024, true);
  951. newStream.Write(index, 0, 10261);
  952. newStream.Flush();
  953. }
  954. #endregion
  955. #region 从一个文件中解密出一段文本
  956. /// <summary>
  957. /// 从一个文件中解密出一段文本,其中,这个文件是由InitBinFile建立的,并且由 EncryptToFile加密的
  958. /// </summary>
  959. /// <param name="filePath">要解密的文件</param>
  960. /// <param name="dataIndex">要从哪一个块中解密</param>
  961. /// <param name="iv">初始化向量</param>
  962. /// <param name="key">解密密匙</param>
  963. /// <returns>解密后的文本</returns>
  964. public static string DecryptFromFile(this string filePath, int dataIndex, byte[] iv, byte[] key)
  965. {
  966. if ((dataIndex > 10) && (dataIndex < 1))
  967. {
  968. return "";
  969. }
  970. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  971. using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
  972. using var msDecrypt = new PooledMemoryStream();
  973. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  974. var index = new byte[10261];
  975. tmpFileStream.Read(index, 0, 10261);
  976. var count = index[dataIndex * 2 - 1] * 128 + index[dataIndex * 2];
  977. var tmp = new byte[count];
  978. Array.Copy(index, 1024 * (dataIndex - 1) + 21, tmp, 0, count);
  979. csDecrypt.Write(tmp, 0, count);
  980. csDecrypt.FlushFinalBlock();
  981. var decrypted = msDecrypt.ToArray();
  982. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  983. }
  984. #endregion
  985. #region 将一段文本加密后保存到一个文件
  986. /// <summary>
  987. /// 将一段文本加密后保存到一个文件
  988. /// </summary>
  989. /// <param name="toEncryptText">要加密的文本数据</param>
  990. /// <param name="filePath">要保存的文件</param>
  991. /// <param name="iv">初始化向量</param>
  992. /// <param name="key">加密密匙</param>
  993. /// <returns>是否加密成功</returns>
  994. public static void EncryptToFile(this string toEncryptText, string filePath, byte[] iv, byte[] key)
  995. {
  996. using var tmpFileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.None, 1024, true);
  997. using var encryptor = _rc2Csp.CreateEncryptor(key, iv);
  998. using var msEncrypt = new PooledMemoryStream();
  999. using var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
  1000. var tmp = _textConverter.GetBytes(toEncryptText);
  1001. csEncrypt.Write(tmp, 0, tmp.Length);
  1002. csEncrypt.FlushFinalBlock();
  1003. var encrypted = msEncrypt.ToArray();
  1004. tmpFileStream.Write(encrypted, 0, encrypted.Length);
  1005. tmpFileStream.Flush();
  1006. }
  1007. #endregion
  1008. #region 将一个被加密的文件解密
  1009. /// <summary>
  1010. /// 将一个被加密的文件解密
  1011. /// </summary>
  1012. /// <param name="filePath">要解密的文件</param>
  1013. /// <param name="iv">初始化向量</param>
  1014. /// <param name="key">解密密匙</param>
  1015. /// <returns>解密后的文本</returns>
  1016. public static string DecryptFromFile(this string filePath, byte[] iv, byte[] key)
  1017. {
  1018. using var tmpFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None, 1024, true);
  1019. using var decryptor = _rc2Csp.CreateDecryptor(key, iv);
  1020. using var msDecrypt = new PooledMemoryStream();
  1021. using var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Write);
  1022. var tmp = new byte[tmpFileStream.Length];
  1023. tmpFileStream.Read(tmp, 0, tmp.Length);
  1024. csDecrypt.Write(tmp, 0, tmp.Length);
  1025. csDecrypt.FlushFinalBlock();
  1026. var decrypted = msDecrypt.ToArray();
  1027. return _textConverter.GetString(decrypted, 0, decrypted.Length);
  1028. }
  1029. #endregion
  1030. #region 设置加密或解密的初始化向量
  1031. /// <summary>
  1032. /// 设置加密或解密的初始化向量
  1033. /// </summary>
  1034. /// <param name="s">长度等于8的ASCII字符集的字符串</param>
  1035. public static void SetIV(this string s)
  1036. {
  1037. if (s.Length != 8)
  1038. {
  1039. _iv = null;
  1040. return;
  1041. }
  1042. try
  1043. {
  1044. _iv = _asciiEncoding.GetBytes(s);
  1045. }
  1046. catch (Exception)
  1047. {
  1048. _iv = null;
  1049. }
  1050. }
  1051. #endregion
  1052. #region 设置加密或解密的密匙
  1053. /// <summary>
  1054. /// 设置加密或解密的密匙
  1055. /// </summary>
  1056. /// <param name="s">长度等于16的ASCII字符集的字符串</param>
  1057. public static void SetKey(this string s)
  1058. {
  1059. if (s.Length != 16)
  1060. {
  1061. _key = null;
  1062. return;
  1063. }
  1064. try
  1065. {
  1066. _key = _asciiEncoding.GetBytes(s);
  1067. }
  1068. catch (Exception)
  1069. {
  1070. _key = null;
  1071. }
  1072. }
  1073. #endregion
  1074. }
  1075. }