问题描述
using (FileStream fileStream = new(filePath,FileMode.OpenorCreate))
{
using (Aes aes = Aes.Create())
{
byte[] key =
{
0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09,0x10,0x11,0x12,0x13,0x14,0x15,0x16
};
aes.Key = key;
byte[] iv = aes.IV;
fileStream.Write(iv,iv.Length);
using (CryptoStream cryptoStream = new(fileStream,aes.CreateEncryptor(),CryptoStreamMode.Write))
{
using (StreamWriter encryptWriter = new(cryptoStream))
{
await input.File.copyToAsync(cryptoStream);
}
}
}
}
using (FileStream fileStream = new(filePath,FileMode.Open))
{
using (Aes aes = Aes.Create())
{
byte[] iv = new byte[aes.IV.Length];
int numBytesToRead = aes.IV.Length;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
int n = fileStream.Read(iv,numBytesRead,numBytesToRead);
if (n == 0) break;
numBytesRead += n;
numBytesToRead -= n;
}
byte[] key =
{
0x01,0x16
};
using (CryptoStream cryptoStream = new(fileStream,aes.CreateDecryptor(key,iv),CryptoStreamMode.Read))
{
// Desired option - not saving unenrypted to disk
var ms = new MemoryStream();
await cryptoStream.copyToAsync(ms);
return new FileStreamResult(ms,"application/pdf");
// TESTING PURPOSES ONLY - saving unenrypted to disk
//var outputStream = new FileStream("C:\\Files\\unencrypted.pdf",FileMode.Create);
//await cryptoStream.copyToAsync(outputStream);
//return new FileStreamResult(outputStream,"application/pdf");
}
}
}
我希望用户能够在浏览器中打开文档,而无需将未加密的文件保存回磁盘。
然而,上面的解密导致以下结果:
未声明纯文本文档的字符编码。如果文档包含来自 US-ASCII 范围之外的字符,则文档将在某些浏览器配置中呈现为乱码。文件的字符编码需要在传输协议中声明或者文件需要使用字节序标记作为编码签名。
注释掉的代码会将未加密的文件保存到磁盘,并且可以从 Windows 资源管理器中打开。但是,在实际应用中运行还是会出现上述错误。
当然,如果 PDF 中的编码正确,那么未加密的版本也应该如此,一旦从流的开头删除了 IV?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)