Encrypt.cs 56 KB

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