17.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, which has a constructor that 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 you can be reasonably assured that this class could be extended to cover all of them. This example implements support for TripleDES and Rijndael.

The following namespaces are needed for this solution:

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

The class SecretFile (implemented in this recipe) can be used for TripleDES as shown:

 // Use TripleDES. using (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 secret data: {0}",decrypt); ...

Get C# 3.0 Cookbook, 3rd Edition 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.