Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Encrypt serialized file before writing to disk

Let's say my program has a class called "customer" and the customer class is serializable so I can read and write it to disk. The customer class holds sensitive information that I want to encrypt, the only way I know I could keep the file safe would be to:

1-Serialize the file to disk

2-Reopen and load the file

3-Encrypt the file

4-Rewrite file to disk

This would work, but there is a risk that the file could be intercepted in it's unencrypted state and furthermore this is just really inefficient.

Instead I would like to:

1-Create file in memory

2-Encrypt file in memory

3-Write encrypted file to disk

Is this possible? If it is how? Thanks in advance.

like image 942
avatarmonkeykirby Avatar asked May 03 '11 13:05

avatarmonkeykirby


1 Answers

You can use a CryptoStream to do the encryption at the same time as you serialize the class to a file:

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);
}
like image 135
Patrick McDonald Avatar answered Sep 18 '22 06:09

Patrick McDonald