我想知道在C#中是否有使用AES加密和解密文件的代码?我看过一些关于使用aes加密和解密c#中的文本的代码但是 加密和解密c#中的文件..没有完整的代码可以理解它。如果有人可以帮助我吗?
答案 0 :(得分:0)
通常,您不想加密文件。也就是说,您不想编写文件,然后对其进行加密。数据可能位于存储设备的不同扇区中,并且可能会被恢复。 (当然,如果您正在尝试编写勒索软件,请务必将其写得很糟糕)。你要做的是在将内容加载到磁盘之前加密内容。
public static void EncryptFile(string filePath, byte[] key)
{
string tempFileName = Path.GetTempFileName();
using (SymmetricAlgorithm cipher = Aes.Create())
using (FileStream fileStream = File.OpenRead(filePath))
using (FileStream tempFile = File.Create(tempFileName))
{
cipher.Key = key;
// aes.IV will be automatically populated with a secure random value
byte[] iv = cipher.IV;
// Write a marker header so we can identify how to read this file in the future
tempFile.WriteByte(69);
tempFile.WriteByte(74);
tempFile.WriteByte(66);
tempFile.WriteByte(65);
tempFile.WriteByte(69);
tempFile.WriteByte(83);
tempFile.Write(iv, 0, iv.Length);
using (var cryptoStream =
new CryptoStream(tempFile, cipher.CreateEncryptor(), CryptoStreamMode.Write))
{
fileStream.CopyTo(cryptoStream);
}
}
File.Delete(filePath);
File.Move(tempFileName, filePath);
}
public static void DecryptFile(string filePath, byte[] key)
{
string tempFileName = Path.GetTempFileName();
using (SymmetricAlgorithm cipher = Aes.Create())
using (FileStream fileStream = File.OpenRead(filePath))
using (FileStream tempFile = File.Create(tempFileName))
{
cipher.Key = key;
byte[] iv = new byte[cipher.BlockSize / 8];
byte[] headerBytes = new byte[6];
int remain = headerBytes.Length;
while (remain != 0)
{
int read = fileStream.Read(headerBytes, headerBytes.Length - remain, remain);
if (read == 0)
{
throw new EndOfStreamException();
}
remain -= read;
}
if (headerBytes[0] != 69 ||
headerBytes[1] != 74 ||
headerBytes[2] != 66 ||
headerBytes[3] != 65 ||
headerBytes[4] != 69 ||
headerBytes[5] != 83)
{
throw new InvalidOperationException();
}
remain = iv.Length;
while (remain != 0)
{
int read = fileStream.Read(iv, iv.Length - remain, remain);
if (read == 0)
{
throw new EndOfStreamException();
}
remain -= read;
}
cipher.IV = iv;
using (var cryptoStream =
new CryptoStream(tempFile, cipher.CreateDecryptor(), CryptoStreamMode.Write))
{
fileStream.CopyTo(cryptoStream);
}
}
File.Delete(filePath);
File.Move(tempFileName, filePath);
}
不是通过FileStream编写原始文件,而是打开文件,编写标题和IV,创建CryptoStream,并使用CryptoStream进行所有操作。没有理由让未加密的表格出现在磁盘上。
答案 1 :(得分:-3)
您需要执行以下加密:
您需要执行以下操作进行解密: