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

ava*_*rby 15 c# encryption serialization

假设我的程序有一个名为"customer"的类,客户类是可序列化的,所以我可以读取并写入磁盘.客户类包含我想要加密的敏感信息,我知道可以保证文件安全的唯一方法是:

1 - 将文件序列化到磁盘

2 - 重新打开并加载文件

3 - 加密文件

4 - 将文件重写到磁盘

这可以工作,但是存在文件可能在其未加密状态下被截获的风险,而且这实际上是非常低效的.

相反,我想:

1 - 在内存中创建文件

2加密内存中的文件

3 - 将加密文件写入磁盘

这可能吗?如果是这样的话?提前致谢.

Pat*_*ald 33

在将类序列化为文件的同时,可以使用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);
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*tka 27

除了注释中表达的关注之外,如果您要问的是如何使用内存中的字节并且只将它们写入文件一次,那么首先将对象序列化为内存流.加密这些字节并将它们写入文件.

using (var fileStream = File.OpenWrite(theFileName))
using (var memoryStream = new MemoryStream())
{
    // Serialize to memory instead of to file
    var formatter = new BinaryFormatter();
    formatter.Serialize(memoryStream, customer);

    // This resets the memory stream position for the following read operation
    memoryStream.Seek(0, SeekOrigin.Begin);

    // Get the bytes
    var bytes = new byte[memoryStream.Length];
    memoryStream.Read(bytes, 0, (int)memoryStream.Length);

    // Encrypt your bytes with your chosen encryption method, and write the result instead of the source bytes
    var encryptedBytes = yourCrypto.Encrypt(bytes);
    fileStream.Write(encryptedBytes, 0, encryptedBytes.Length);
}
Run Code Online (Sandbox Code Playgroud)