我需要实现一个简单的文件加密,然后在需要时将其解密为内存流。 最简单的方法似乎是使用 File.Encrypt 执行此操作,但是否可以将文件解密到内存流,而不是在将文件读取到内存流之前解密文件,从而将其公开一段时间?
如果 File.Encrypt 不是这种情况下的最佳方式,您会推荐什么?
最佳答案
File.Encrypt
是一项操作系统功能,但听起来您确实想要控制加密的完成方式。
http://msdn.microsoft.com/en-us/library/system.io.file.encrypt.aspx
// This is where the data will be written do.
MemoryStream dataStream = new MemoryStream();
// The encryption vectors
byte[] key = {145,12,32,245,98,132,98,214,6,77,131,44,221,3,9,50};
byte[] iv = {15,122,132,5,93,198,44,31,9,39,241,49,250,188,80,7};
// Build the encryption mathematician
using (TripleDESCryptoServiceProvider encryption = new TripleDESCryptoServiceProvider())
using (ICryptoTransform transform = encryption.CreateEncryptor(key, iv))
using (Stream encryptedOutputStream = new CryptoStream(dataStream, transform, CryptoStreamMode.Write))
using (StreamWriter writer = new StreamWriter(encryptedOutputStream))
{
// In this block, you do your writing, and it will automatically be encrypted
writer.Write("This is the encrypted output data I want to write");
}
加密不适合胆小的人。不过请注意,在尝试此操作之前,您确实应该对常规 IO 和数据流有很强的了解。
关于c# - 使用 File.Encrypt 加密文件,然后将其解密到内存流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14777732/