使用File.Encrypt加密文件,然后将其解密到内存流 [英] Encrypt a file using File.Encrypt and then Decrypt it to memory stream

查看:176
本文介绍了使用File.Encrypt加密文件,然后将其解密到内存流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要实现简单的文件加密,然后在需要时将其解密到内存流中. 最简单的方法似乎是使用File.Encrypt来做到这一点,但是是否可以将文件解密到内存流中,而不是在将文件读取到内存流中之前解密文件,从而使其暴露一会儿?

I need to implement a simple file encryption and then decrypt it, when needed, to a memory stream. The easiest way seems to do this with File.Encrypt, but is it possible to decrypt the file to memory stream, instead of decrypting the file before reading it to memory stream, and thus exposing it for a while?

如果File.Encrypt不是这种情况下的最佳方法,那么您会推荐什么?

And if File.Encrypt is not the best way for this scenario, what would you recommend?

推荐答案

File.Encrypt是一项操作系统功能,但听起来您确实想控制加密的完成方式.

File.Encrypt is an OS feature but it sounds like really you want to control how the encryption is done.

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和数据流有强烈的了解.

Encryption is not for the faint of heart. Be forewarned though, you really should have a strong sense of regular IO and data streams before you attempt this though.

这篇关于使用File.Encrypt加密文件,然后将其解密到内存流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆