c# - 使用 File.Encrypt 加密文件,然后将其解密到内存流

标签 c# file memory encryption

我需要实现一个简单的文件加密,然后在需要时将其解密为内存流。 最简单的方法似乎是使用 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/

相关文章:

C++:从复制构造函数外部修改对象成员时 vector 内存损坏,但从内部修改时则不会

c# - 在 HoloLens 1 上,在使用默认构造函数 "ArgumentException: Value does not fall within the expected range"创建 TcpClient 对象时抛出

c# - 在 C# 中使用委托(delegate)作为属性是否正确?

java - 如何从客户端访问服务器C盘下的文件?

python - 读取存储在文本文件中的列表

c++ - AIX 中的编程内存监视

c# - 如何获取代码或堆栈跟踪?

c# - 一个 WCF 服务可以返回另一个吗?

java - File.toURI 不编码加号

postgresql - 索引中如何发生碎片?