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); ...Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access