Skip to Content
C# Cookbook
book

C# Cookbook

by Stephen Teilhet, Jay Hilyard
January 2004
Beginner to intermediate
864 pages
22h 18m
English
O'Reilly Media, Inc.
Content preview from C# Cookbook

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 ...
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.
Start your free trial

You might also like

C# Cookbook

C# Cookbook

Joe Mayo
C# Cookbook, 2nd Edition

C# Cookbook, 2nd Edition

Jay Hilyard, Stephen Teilhet
ASP.NET Cookbook

ASP.NET Cookbook

Michael A Kittel, Geoffrey T. LeBlond

Publisher Resources

ISBN: 0596003390Supplemental ContentCatalog PageErrata