Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.

Channels ▼


Sensitive Data & the .NET Crypto API

Source Code Accompanies This Article. Download It Now.

December, 2004: Sensitive Data & the .NET Crypto API

Safeguarding sensitive data isn't just a good idea, it's the law

Between them, David and Eric have developed everything from Windows applications for travel agents to electronic publishing software. They can be contacted at [email protected] and [email protected] comcast.net, respectively.

Cryptography Export Restrictions

Criminals are prowling the Internet looking for data to steal. Will your data or your customers' be next? The bad guys don't care about data security laws, but software professionals need to know their legal obligation to keep customer data private. Properly using the .NET Cryptography API is an effective way to safeguard sensitive data. In this article, we show you how to choose the right crypto algorithm, generate keys and initialization vectors, and encrypt/decrypt objects and byte arrays. We also include a sample application that demonstrates these techniques.

If sensitive data is stored on a hard disk, in a database, or in any other persistent format, it is imperative to encrypt it with a strong encryption algorithm. Even if your organization controls physical access to your data center, private data can leave the data center in a variety of ways. Backups are often stored in offsite locations. Computers are shipped off for repair or disposal. In a study entitled "A Remembrance of Data Passed," two MIT graduate students analyzed 158 hard drives purchased on eBay. Of the 129 drives that were functional, 74 percent contained easily recoverable data including financial records, medical information, e-mail correspondence, and thousands of credit-card numbers. Only 12 of the disks were properly erased (see http://web.mit.edu/newsoffice/ 2003/diskdrives.html).

Safeguarding confidential data isn't just a good idea, it's the law. For example, California's SB 1386 law mandates that businesses publicly disclose security breaches if a Californian's confidential information may have been compromised. This law doesn't just affect California-based businesses; it applies to any company with customers in California. The U.S. federal HIPAA law requires all U.S. organizations to protect electronic patient health data. The European Union imposes strict policies for securing EU citizen data. (Also see the accompanying text box entitled "Cryptography Export Restrictions.") Fortunately, .NET's cryptography API lets you secure your data with ease.

The sample application we present here (see Figure 1) is a .NET Windows Forms program written in C# (available electronically; see "Resource Center," page 5). It requires the .NET 1.1 Framework and Windows 2000/XP or later. It includes a regression test suite developed with NUnit (http://www.nunit.org/). Build it in Visual Studio .NET 2003 by opening Crypto\Crypto.sln, or install it by running setup.exe in the setup folder. Then launch the application and try it out.

The user ID and password are used to generate an initialization vector and encryption key, respectively. Select an algorithm from the drop-down list. Press Encrypt to convert the unencrypted text (plaintext) to encrypted ciphertext. Press Decrypt to convert the ciphertext back to plaintext.


The first step to encrypting data is to create a key, which is simply a series of bits. Since the strength of a cryptographic algorithm is proportional to the key length, it's important to create a key with a sufficient number of bits. The code in this article uses 128-bit keys. Most users would rather remember a password string than a 128-bit key, so call the MD5CryptoServiceProvider's ComputeHash method to convert a password into a 128-bit key (Listing One).

A key is only as strong as the password that was used to generate it. Passwords that are simply words leave the encrypted data vulnerable to dictionary attacks. A dictionary attack iterates through each word in a word list, generates the corresponding key, and attempts to decrypt the data. Reduce your vulnerability by requiring users to enter one or more digits in their passwords, and require reasonably long passwords.

You'll need to instantiate a Crypto object to get started. This object uses the RijndaelManaged cryptography algorithm by default. You can specify another SymmetricAlgorithm by specifying that algorithm in the constructor, or assigning it to the object's Algorithm property. The sample app also supports the RC2 and TripleDES algorithms.

We deliberately don't support the DES algorithm because it's too weak. DES uses short 56-bit keys, which render it vulnerable to "brute force" attacks. If you can get enough machines to test each of the 256 keys, you can crack the code. The RSA Data Security company sponsors contests to break DES-encrypted ciphertext. The 1999 contest winner cracked the DES-encrypted ciphertext in only 22 hours (http://www.rsasecurity.com/press_release .asp?doc_id=462).

Crypto.EncryptByteArray (Listing Two) encrypts a byte array using the specified user ID and password. The first step is to generate a key and initialization vector using the HashPassword method. The initialization vector ensures that two plaintext messages that start with the same text generate completely different ciphertext. You can see how initialization vectors change the ciphertext by running the sample app. Encrypt the plaintext, then change just the user ID and encrypt again. You'll see the ciphertext completely change when you press Encrypt the second time. Unlike keys, it's not important to keep initialization vectors secret.

Once the key and initialization vector are ready, call the cryptography algorithm's CreateEncryptor method to create an encryptor object. Then create a MemoryStream and use it to create a CryptoStream. When the byte array is written to the CryptoStream, it's encrypted. The call to FlushFinalBlock ensures that the last section of plaintext is encrypted. Calling the MemoryStream's ToArray method converts the entire ciphertext to a byte array.

Any object that implements the ISerializable interface can be encrypted using Crypto.EncryptObject. EncryptObject first converts the object to a byte array by calling SerializeObjectToByteArray. Then Crypto.EncryptByteArray is called to encrypt the byte array.

Call Crypto.DecryptByteArray to decrypt a byte array (Listing Three). DecryptByteArray creates a key, initialization vector, and a decryptor. Then it creates a MemoryStream containing the ciphertext, and a CryptoStream that uses the MemoryStream. It repeatedly calls the CryptoStream's Read method to decrypt consecutive sections of the byte array. Each section of the byte array is appended to the plainText ArrayList. When the entire byte array has been decrypted, it is returned by calling plainText.ToArray.

Crypto.DecryptObject converts an encrypted byte array back to the original object. First, the ciphertext byte array is decrypted. Then, it's converted back to the original object by calling SerializeByteArrayToObject.

Once you've encrypted the data, it is sometimes necessary to store it in a non-binary format. A good example is XML. The best way to store this kind of binary data inside of XML and other character-sensitive formats is to encode it such that there are no offending characters (such as "<" or ">") in the data. Base64 encoding is a good method for doing this. It takes binary data and encodes it in text form using only A-Z, a-z, 0-9, +, /, and =. The .NET Framework provides a simple method to convert to and from Base64 encodings: Convert.ToBase64String and Convert.FromBase64String.

If your ASP.NET web application stores sensitive data in a database, you'll want to encrypt the database (or just the sensitive data if it's a small percentage of the total data). If you're using Microsoft SQL Server for cross-server session management, your session data will be made persistent to the database. ASP.NET provides a way to automatically encrypt the stored session data. Data stored with ASP.NET's ViewState feature is also automatically encrypted, but tends to bloat your site's web pages. Finally, there are cookies. Cookies have a limit of 4 KB and users can disable them, but they can be a handy way to store data (including sensitive data). Encrypting the data before storing it in any of these, or other, places can protect that data and save you from embarrassment or worse.

When making data persistent, it can be useful to store whole objects and then restore them back to their original state when reading them. Serialization in .NET is made easy with the ISerializable interface, which is implemented by many classes in the .NET Framework. If you want to encrypt an object's data before it becomes persistent, then you have a little bit of work to do. The easiest and most efficient way to do this is to serialize the object to a byte array using a BinaryFormatter, encrypt the byte array, and then Base64 encode the resulting string. Then you reverse the process when retrieving the data (Listing Four).

Given how easy encryption is in .NET, the most difficult thing is determining what constitutes sensitive information. Most will be obvious, such as credit-card numbers and passwords. But what about street addresses, phone numbers, and other similar information? Also, remember to examine your application for possible loopholes. For example, even after temporary files are deleted, the bits are still on the hard drive and are vulnerable. In today's environment, you have both a moral and legal obligation to secure any sensitive data that will persist to a hard drive. You'll want to make sure that you adequately protect that data before releasing your application.


Listing One

// Used to convert strings to byte arrays.
private Encoding encoding = new UnicodeEncoding();

// Used to hash passwords and user ids into encryption keys.
private HashAlgorithm hashAlgorithm = new MD5CryptoServiceProvider();

private byte[] HashPassword(String text)
  return hashAlgorithm.ComputeHash(encoding.GetBytes(text));
Back to article

Listing Two
public byte[] EncryptByteArray(string userID, string password, 
                                                   byte[] plainTextBuffer)
  // Create key and initialization vector.
  key = HashPassword(password);
  iv  = HashPassword(userID);

  byte[] cipherTextBuffer = null;

  // Create Encryptor and encrypt the data.
  using (ICryptoTransform encryptor = algorithm.CreateEncryptor(key, iv))
  using (MemoryStream memoryStream = new MemoryStream())
  using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, 
    //Write all data to the crypto stream and flush it.
    cryptoStream.Write(plainTextBuffer, 0, plainTextBuffer.Length);

    //Get encrypted array of bytes.
    cipherTextBuffer = memoryStream.ToArray();
  return cipherTextBuffer;
public byte[] EncryptObject(string userID, string password, object obj)
  // Convert the object to a byte array.
  byte[] plainTextBuffer =
  // Encrypt it.
  return EncryptByteArray(userID, password, plainTextBuffer);
Back to article

Listing Three
public byte[] DecryptByteArray(string userID, string password, 
                               byte[] cipherTextBuffer)
  // Create key and initialization vector.
  key = HashPassword(password);
  iv  = HashPassword(userID);

  ArrayList plainText = new ArrayList(cipherTextBuffer.Length);

  // Create Decryptor and decrypt the data.
  using (ICryptoTransform decryptor = algorithm.CreateDecryptor(key, iv))
  using (MemoryStream memoryStream = new MemoryStream(cipherTextBuffer))
  using (CryptoStream cryptoStream = 
          new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
    byte[] buffer = new byte[cipherTextBuffer.Length];
    int bytesRead;
    // Read plaintext from cryptostream until all plaintext has been extracted.
      bytesRead = cryptoStream.Read(buffer, 0, buffer.Length);
      if (bytesRead > 0)
        // Copy the bytes actually read into the plainText ArrayList.
        byte[] bufferRead = new byte[bytesRead];
        Array.Copy(buffer, 0, bufferRead, 0, bytesRead);

    } while (bytesRead > 0);
  return (byte[]) plainText.ToArray(typeof(byte));
public object DecryptObject(string userID, string password, 
                            byte[] cipherTextBuffer)
  // Decrypt the byte array.
  byte[] plainTextBuffer = DecryptByteArray(userID,password,cipherTextBuffer);
  // Convert decrypted byte array to an object.
  return serializeDeserialize.SerializeByteArrayToObject(
            plainTextBuffer, plainTextBuffer.Length);
Back to article

Listing Four
private string Serialize(object obj)
  string result = "";
  BinaryFormatter Formatter = new BinaryFormatter();
  using (MemoryStream memoryStream = new MemoryStream())
    // Serialize the object to a byte array.
    Formatter.Serialize(memoryStream, obj);
    // Get ready to read the stream into a byte array.
    memoryStream.Seek(0, SeekOrigin.Begin);
    byte[] buffer = new byte[memoryStream.Length];
    // Read the stream into the byte array.
    int bytesRead = memoryStream.Read(buffer, 0, buffer.Length);
    // Encrypt the byte array
    buffer = EncryptByteArray(buffer);
    //Return the result as a Base64 string
    //  Base64 is only necessary if storing in XML
    //  or other text-based formats
    result = Convert.ToBase64String(buffer, 0, bytesRead);
  return result;
private object Deserialize(string str)
  object obj = null;
  BinaryFormatter Formatter = new BinaryFormatter();
  // Convert from a Base64 string
  byte[] buffer = Convert.FromBase64String(str);
  // Decrypt the byte array
  buffer = DecryptByteArray(buffer);
  // Convert the byte array to a MemoryStream
  using (MemoryStream memoryStream = new MemoryStream(buffer,0,buffer.Length))
    // Convert the MemoryStream to an object
    obj = Formatter.Deserialize(memoryStream);
  return obj;
Back to article

Related Reading

More Insights

Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.