1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Security.Cryptography;
- using System.IO;
- namespace Welling_Motor_Debug_Tool
- {
- internal class aes
- {
- // 加密函数
- public static void EncryptToFile(string plainText, string filePath, string key, string iv)
- {
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Encoding.UTF8.GetBytes(key); // 密钥(必须是 16、24 或 32 字节)
- aesAlg.IV = Encoding.UTF8.GetBytes(iv); // 初始化向量(IV,必须是 16 字节)
- using (FileStream fsEncrypt = new FileStream(filePath, FileMode.Create))
- using (CryptoStream csEncrypt = new CryptoStream(fsEncrypt, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
- using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
- {
- swEncrypt.Write(plainText);
- }
- }
- }
- // 解密函数
- public static string DecryptFromFile(string filePath, string key, string iv)
- {
- using (Aes aesAlg = Aes.Create())
- {
- aesAlg.Key = Encoding.UTF8.GetBytes(key); // 密钥(必须是 16、24 或 32 字节)
- aesAlg.IV = Encoding.UTF8.GetBytes(iv); // 初始化向量(IV,必须是 16 字节)
- using (FileStream fsDecrypt = new FileStream(filePath, FileMode.Open))
- using (CryptoStream csDecrypt = new CryptoStream(fsDecrypt, aesAlg.CreateDecryptor(), CryptoStreamMode.Read))
- using (StreamReader srDecrypt = new StreamReader(csDecrypt))
- {
- return srDecrypt.ReadToEnd();
- }
- }
- }
- }
- }
|