aes.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Security.Cryptography;
  7. using System.IO;
  8. namespace Welling_Motor_Debug_Tool
  9. {
  10. internal class aes
  11. {
  12. // 加密函数
  13. public static void EncryptToFile(string plainText, string filePath, string key, string iv)
  14. {
  15. using (Aes aesAlg = Aes.Create())
  16. {
  17. aesAlg.Key = Encoding.UTF8.GetBytes(key); // 密钥(必须是 16、24 或 32 字节)
  18. aesAlg.IV = Encoding.UTF8.GetBytes(iv); // 初始化向量(IV,必须是 16 字节)
  19. using (FileStream fsEncrypt = new FileStream(filePath, FileMode.Create))
  20. using (CryptoStream csEncrypt = new CryptoStream(fsEncrypt, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
  21. using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
  22. {
  23. swEncrypt.Write(plainText);
  24. }
  25. }
  26. }
  27. // 解密函数
  28. public static string DecryptFromFile(string filePath, string key, string iv)
  29. {
  30. using (Aes aesAlg = Aes.Create())
  31. {
  32. aesAlg.Key = Encoding.UTF8.GetBytes(key); // 密钥(必须是 16、24 或 32 字节)
  33. aesAlg.IV = Encoding.UTF8.GetBytes(iv); // 初始化向量(IV,必须是 16 字节)
  34. using (FileStream fsDecrypt = new FileStream(filePath, FileMode.Open))
  35. using (CryptoStream csDecrypt = new CryptoStream(fsDecrypt, aesAlg.CreateDecryptor(), CryptoStreamMode.Read))
  36. using (StreamReader srDecrypt = new StreamReader(csDecrypt))
  37. {
  38. return srDecrypt.ReadToEnd();
  39. }
  40. }
  41. }
  42. }
  43. }