O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

14.4. Cleaning Up Cryptography Information

Problem

You will be using the cryptography classes in the FCL to encrypt and/or decrypt data. In doing so, you want to make sure that no data (e.g., seed values or keys) is left in memory for longer than you are using the cryptography classes. Hackers can sometimes find this information in memory and use it to break your encryption; or worse, to break your encryption, modify the data, and then re-encrypt the data and pass it on to your application.

Solution

In order to clear out the key and initialization vector (or seed), we need to call the Clear method on whichever SymmetricAlgorithm derived or AsymmetricAlgorithm derived class we are using. Clear reinitializes the Key and IV properties preventing them from being found in memory. This is done after saving the key and IV so that we can decrypt later. The following example shows a series of actions that encodes a string and uses this approach to clean up immediately after the encryption is performed to provide the smallest window possible for potential attackers:

using System; using System.Text; using System.IO; using System.Security.Cryptography; string originalStr = "SuperSecret information"; // Encode data string to be stored in memory byte[] originalStrAsBytes = Encoding.ASCII.GetBytes(originalStr); byte[] originalBytes = {}; // create MemoryStream to contain output MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length); RijndaelManaged rijndael = new RijndaelManaged( ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required