14.3. Encrypting and Decrypting a File

Problem

You have sensitive information that must be encrypted before it is written to a file that might be in a nonsecure area. This information must also be decrypted before it is read back in to the application.

Solution

Use multiple cryptography providers and write the data to a file in encrypted format. This is accomplished in the following class, whose constructor expects an instance of the System.Security.Cryptography.SymmetricAlgorithm class and a path for the file. The SymmetricAlgorithm class is an abstract base class for all cryptographic providers in .NET, so we can be reasonably assured that this class could be extended to cover all of them. This example implements support for TripleDES and Rijndael. It could easily be extended for DES and RC2, which are also provided by the framework.

The following namespaces are needed for this solution:

using System;
using System.Text;
using System.IO;
using System.Security.Cryptography;

The class SecretFile can be used for TripleDES as shown:

// Use TripleDES TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider( ); SecretFile secretTDESFile = new SecretFile(tdes,"tdestext.secret"); string encrypt = "My TDES Secret Data!"; Console.WriteLine("Writing secret data: {0}",encrypt); secretTDESFile.SaveSensitiveData(encrypt); // save for storage to read file byte [] key = secretTDESFile.Key; byte [] IV = secretTDESFile.IV; string decrypt = secretTDESFile.ReadSensitiveData( ); Console.WriteLine("Read ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.