Cryptography.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace UploadClient
  9. {
  10. public class Cryptography
  11. {
  12. #region 可逆加密
  13. /// <summary>
  14. /// 加密——秘钥必须8位
  15. /// </summary>
  16. /// <param name="data"></param>
  17. /// <param name="KEYStr"></param>
  18. /// <param name="IVStr"></param>
  19. /// <returns></returns>
  20. public static string Encode(string data, string KEYStr = "qnet9ew!", string IVStr = "56431212")
  21. {
  22. byte[] byKey = Encoding.ASCII.GetBytes(KEYStr);
  23. byte[] byIV = Encoding.ASCII.GetBytes(IVStr);
  24. using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
  25. {
  26. int i = cryptoProvider.KeySize;
  27. using (MemoryStream ms = new MemoryStream())
  28. {
  29. using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write))
  30. {
  31. using (StreamWriter sw = new StreamWriter(cst))
  32. {
  33. sw.Write(data);
  34. sw.Flush();
  35. cst.FlushFinalBlock();
  36. sw.Flush();
  37. return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
  38. }
  39. }
  40. }
  41. }
  42. }
  43. /// <summary>
  44. /// 解密——秘钥必须8位
  45. /// </summary>
  46. /// <param name="data"></param>
  47. /// <param name="KEYStr"></param>
  48. /// <param name="IVStr"></param>
  49. /// <returns></returns>
  50. public static string Decode(string data, string KEYStr = "qnet9ew!", string IVStr = "56431212")
  51. {
  52. byte[] byKey = Encoding.ASCII.GetBytes(KEYStr);
  53. byte[] byIV = Encoding.ASCII.GetBytes(IVStr);
  54. byte[] byEnc;
  55. try
  56. {
  57. byEnc = Convert.FromBase64String(data);
  58. }
  59. catch
  60. {
  61. return null;
  62. }
  63. using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider())
  64. {
  65. using (MemoryStream ms = new MemoryStream(byEnc))
  66. {
  67. using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read))
  68. {
  69. using (StreamReader sr = new StreamReader(cst))
  70. {
  71. return sr.ReadToEnd();
  72. }
  73. }
  74. }
  75. }
  76. }
  77. #endregion
  78. }
  79. }