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( ...

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.