17.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 reencrypt the data and pass it on to your application.
Solution
In order to clear out the key and initialization vector (or seed), you need to call the Clear method on whichever SymmetricAlgorithm- or AsymmetricAlgorithm-derived class you 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 you can decrypt later. Recipe 17.4 encodes a string and then cleans up immediately afterward to provide the smallest window possible for potential attackers.
Example 17-7. Cleaning up cryptography information
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); // Create MemoryStream to contain output. MemoryStream memStream = new MemoryStream(originalStrAsBytes.Length); RijndaelManaged rijndael = new RijndaelManaged( ); // Generate secret key and init vector. rijndael.KeySize = 256; ...
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