Encrypt.cs 58 KB

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