我有本地存储的文件和使用aes加密。
我需要代码中解密形式的文档之一作为流。 我来回尝试,但无法使其工作。
该方法必须是什么样子,以便我可以用解密的内容取回流。
public Stream DecryptFile(string filePath){..??..}
我的加密方法如下:
public async Task EncryptAndSaveFileAsync(Stream stream, string filePath)
{
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
var tempFilePath = Path.GetTempFileName();
try
{
if (!stream.CanRead)
{
stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
}
await using (var tempFileStream = new FileStream(tempFilePath, FileMode.Create, FileAccess.Write))
{
await stream.CopyToAsync(tempFileStream);
}
fileStream.Close();
try
{
await using var inputFileStream = new FileStream(tempFilePath, FileMode.Open, FileAccess.Read);
await using (var outputFileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
using var aesAlg = Aes.Create();
aesAlg.Key = _key;
aesAlg.IV = new byte[16];
await using var cryptoStream = new CryptoStream(outputFileStream, aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV), CryptoStreamMode.Write);
await inputFileStream.CopyToAsync(cryptoStream);
}
inputFileStream.Close();
}
catch (Exception ex)
{
Console.WriteLine("Fehler beim Verschlüsseln der Datei: " + ex.Message);
}
}
catch (Exception ex)
{
// TODO FM Logging
}
finally
{
File.Delete(tempFilePath);
}
}
您的加密代码一开始就是错误的:
cryptoStream
。IV
,它是安全生成的,需要存在以保证算法的安全。CreateEncryptor
是没有意义的,这是默认值。public async Task EncryptAndSaveFileAsync(Stream stream, string filePath)
{
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write);
using var aesAlg = Aes.Create();
aesAlg.Key = _key;
await fileStream.WriteAsync(aesAlg.IV.AsMemory());
await using var cryptoStream = new CryptoStream(fileStream, aesAlg.CreateEncryptor(), CryptoStreamMode.Write);
await inputFileStream.CopyToAsync(cryptoStream);
}
那么解密反过来也是一样的。
public async Task<Stream> DecryptFile(string filePath)
{
await using var fileStream = File.OpenRead(filePath);
using var aesAlg = Aes.Create();
aesAlg.Key = _key;
var iv = new byte[16];
await fileStream.ReadExactlyAsync(_iv.AsMemory());
aesAlg.IV = iv;
await using var cryptoStream = new CryptoStream(fileStream, aesAlg.CreateEncryptor(), CryptoStreamMode.Read);
var mem = new MemoryStream();
await cryptoStream.CopyToAsync(mem);
return mem;
}