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