AES.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Security.Cryptography;
  6. using System.IO;
  7. namespace Bowin.Common
  8. {
  9. public class AES
  10. {
  11. //默认密钥向量
  12. private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
  13. /// <summary>
  14. /// DES加密字符串
  15. /// </summary>
  16. /// <param name="encryptString">待加密的字符串</param>
  17. /// <param name="encryptKey">加密密钥,要求为8位</param>
  18. /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
  19. public static string EncryptDES(string encryptString, string encryptKey)
  20. {
  21. try
  22. {
  23. byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
  24. byte[] rgbIV = Keys;
  25. byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
  26. DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
  27. MemoryStream mStream = new MemoryStream();
  28. CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey,
  29. rgbIV), CryptoStreamMode.Write);
  30. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  31. cStream.FlushFinalBlock();
  32. return Convert.ToBase64String(mStream.ToArray());
  33. }
  34. catch
  35. {
  36. return encryptString;
  37. }
  38. }
  39. /// <summary>
  40. /// DES解密字符串
  41. /// </summary>
  42. /// <param name="decryptString">待解密的字符串</param>
  43. /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
  44. /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
  45. public static string DecryptDES(string decryptString, string decryptKey)
  46. {
  47. try
  48. {
  49. byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
  50. byte[] rgbIV = Keys;
  51. byte[] inputByteArray = Convert.FromBase64String(decryptString);
  52. DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
  53. MemoryStream mStream = new MemoryStream();
  54. CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey,
  55. rgbIV), CryptoStreamMode.Write);
  56. cStream.Write(inputByteArray, 0, inputByteArray.Length);
  57. cStream.FlushFinalBlock();
  58. return Encoding.UTF8.GetString(mStream.ToArray());
  59. }
  60. catch
  61. {
  62. return decryptString;
  63. }
  64. }
  65. }
  66. }