用C# 写一个用于文本文件加密和解密的方法
时间: 2024-01-26 21:04:34 浏览: 25
以下是一个简单的C#文本文件加密和解密的方法,使用了AES加密算法:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public static class FileEncryption
{
private static readonly byte[] Salt = Encoding.ASCII.GetBytes("This is a salt phrase");
public static void EncryptFile(string inputFile, string outputFile, string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
{
using (FileStream fsEncrypted = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
{
using (Aes aes = Aes.Create())
{
Rfc2898DeriveBytes keyDerivationFunction = new Rfc2898DeriveBytes(passwordBytes, Salt, 1000);
aes.Key = keyDerivationFunction.GetBytes(aes.KeySize / 8);
aes.IV = keyDerivationFunction.GetBytes(aes.BlockSize / 8);
fsEncrypted.Write(Salt, 0, Salt.Length);
using (CryptoStream cs = new CryptoStream(fsEncrypted, aes.CreateEncryptor(), CryptoStreamMode.Write))
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = fsInput.Read(buffer, 0, buffer.Length)) > 0)
{
cs.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
public static void DecryptFile(string inputFile, string outputFile, string password)
{
byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
using (FileStream fsInput = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
{
byte[] salt = new byte[Salt.Length];
fsInput.Read(salt, 0, salt.Length);
using (FileStream fsDecrypted = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
{
using (Aes aes = Aes.Create())
{
Rfc2898DeriveBytes keyDerivationFunction = new Rfc2898DeriveBytes(passwordBytes, salt, 1000);
aes.Key = keyDerivationFunction.GetBytes(aes.KeySize / 8);
aes.IV = keyDerivationFunction.GetBytes(aes.BlockSize / 8);
using (CryptoStream cs = new CryptoStream(fsInput, aes.CreateDecryptor(), CryptoStreamMode.Read))
{
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = cs.Read(buffer, 0, buffer.Length)) > 0)
{
fsDecrypted.Write(buffer, 0, bytesRead);
}
}
}
}
}
}
}
```
使用示例:
```csharp
string inputFile = @"C:\plaintext.txt";
string encryptedFile = @"C:\encrypted.dat";
string decryptedFile = @"C:\decrypted.txt";
string password = "MySecretPassword";
FileEncryption.EncryptFile(inputFile, encryptedFile, password);
FileEncryption.DecryptFile(encryptedFile, decryptedFile, password);
```
注意:这只是一个简单的示例,实际应用中需要更复杂的加密和解密方法来确保数据的安全。