use*_*346 6 c# memory encryption file
我需要实现一个简单的文件加密,然后在需要时将其解密到内存流.最简单的方法似乎是使用File.Encrypt执行此操作,但是是否可以将文件解密为内存流,而不是在将文件读取到内存流之前解密文件,从而将文件暴露一段时间?
如果File.Encrypt不是这种情况的最佳方式,你会推荐什么?
这是我编写的第一个加密代码 - 请注意,尽管这是了解正在发生的事情的一个很好的起点,但静态密码和静态盐不是一个好主意!(感谢您强调此 CodesInChaos)
您可以解密到任何您喜欢的流,包括直接解密到内存流......
FileInfo file = new FileInfo("SomeFile");
using (FileStream inFs = file.OpenRead())
{
using (MemoryStream outMs = new MemoryStream())
{
encryption.Decrypt(inFs, outMs);
BinaryFormatter bf = new BinaryFormatter();
targetType target= bf.Deserialize(outMs) as targetType;
}
}
Run Code Online (Sandbox Code Playgroud)
其中加密是其中之一:
public class EncryptionHelper
{
static SymmetricAlgorithm encryption;
static string password = "password";
static string salt = "this is my salt. There are many like it, but this one is mine.";
static EncryptionHelper()
{
encryption = new RijndaelManaged();
Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, Encoding.ASCII.GetBytes(salt));
encryption.Key = key.GetBytes(encryption.KeySize / 8);
encryption.IV = key.GetBytes(encryption.BlockSize / 8);
encryption.Padding = PaddingMode.PKCS7;
}
public void Encrypt(Stream inStream, Stream OutStream)
{
ICryptoTransform encryptor = encryption.CreateEncryptor();
inStream.Position = 0;
CryptoStream encryptStream = new CryptoStream(OutStream, encryptor, CryptoStreamMode.Write);
inStream.CopyTo(encryptStream);
encryptStream.FlushFinalBlock();
}
public void Decrypt(Stream inStream, Stream OutStream)
{
ICryptoTransform encryptor = encryption.CreateDecryptor();
inStream.Position = 0;
CryptoStream encryptStream = new CryptoStream(inStream, encryptor, CryptoStreamMode.Read);
encryptStream.CopyTo(OutStream);
OutStream.Position = 0;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19307 次 |
| 最近记录: |