gpt4 book ai didi

C# 在写入磁盘之前加密序列化文件

转载 作者:可可西里 更新时间:2023-11-01 03:11:53 26 4
gpt4 key购买 nike

假设我的程序有一个名为“customer”的类,并且该客户类是可序列化的,因此我可以读取它并将其写入磁盘。客户类包含我想要加密的敏感信息,我知道我可以保证文件安全的唯一方法是:

1-Serialize the file to disk

2-Reopen and load the file

3-Encrypt the file

4-Rewrite file to disk

这可行,但存在文件在未加密状态下可能被拦截的风险,而且效率非常低。

相反,我想:

1-Create file in memory

2-Encrypt file in memory

3-Write encrypted file to disk

这可能吗?如果是怎么办?提前致谢。

最佳答案

您可以在将类序列化为文件的同时使用 CryptoStream 进行加密:

byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8 }; // Where to store these keys is the tricky part, 
// you may need to obfuscate them or get the user to input a password each time
byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
string path = @"C:\path\to.file";

DESCryptoServiceProvider des = new DESCryptoServiceProvider();

// Encryption
using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(fs, des.CreateEncryptor(key, iv), CryptoStreamMode.Write))
{
BinaryFormatter formatter = new BinaryFormatter();

// This is where you serialize the class
formatter.Serialize(cryptoStream, customClass);
}

// Decryption
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
using (var cryptoStream = new CryptoStream(fs, des.CreateDecryptor(key, iv), CryptoStreamMode.Read))
{
BinaryFormatter formatter = new BinaryFormatter();

// This is where you deserialize the class
CustomClass deserialized = (CustomClass)formatter.Deserialize(cryptoStream);
}

关于C# 在写入磁盘之前加密序列化文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5869922/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com