Thursday, April 07, 2011

C# Tutorial - Triple DES Encryption

The Data Encryption Standard (DES) has been around since the 70's, enjoyed wide-spread adoption, and has since been retired due to its small key length and ease of brute-force attacks. Triple DES, which is basically the same approach times three, aimed to remove the practicality of attacks while keeping the same basic algorithm. Although it's slowly being replaced by AES, triple DES is still a viable approach for your basic encryption needs.

.NET provides everything we'll need in the form of the TripleDESCryptoServiceProvider Class. In this tutorial, we're going to use this object to encrypt and decrypt the contents of a file.

1. Create Key
Triple DES is a symmetric-key algorithm, which means we only need one private key to both encrypt and decrypt. This reduces the complexity of using this algorithm and makes it perfect for simple file encryption. Keys are supposed to be as random as possible, and I would highly recommend using the helper functions provided by .NET to create them. Besides the key, the algorithm also needs an initialization vector, which we can also generate using .NET.
using System.Security.Cryptography;
...
var crypto = new TripleDESCryptoServiceProvider();
crypto.GenerateKey();
crypto.GenerateIV();
Debug.WriteLine(string.Join(",", crypto.Key));
Debug.WriteLine(string.Join(",", crypto.IV));
// Key:
// 144,24,138,199,76,214,156,202,
// 215,2,80,234,152,204,95,48,
// 245, 68,36,8,104,231,212,199
// IV:
// 107,78,8,71,32,44,210,59
You only need to run this code once to generate the keys. Once you've got them, keep them safe and make sure you don't put them where someone whose not supposed to read your encrypted data can see them. Now it's time to use these to actually do some encrypting.

2. Encrypt a File
The first thing we need to do is put the key and initialization vector in our code somewhere.
namespace TripleDESTutorial
{
   class Program
   {
      /// <summary>
      /// Encryption key.
      /// </summary>
      private static readonly byte[] KEY = new byte[]
      {
         144,24,138,199,76,214,156,202,
         215,2,80,234,152,204,95,48,
         245,68,36,8,104,231,212,199
      };
      /// <summary>
      /// Encryption initialization vector.
      /// </summary>
      private static readonly byte[] IV = new byte[]
      {
         107,78,8,71,32,44,210,59
      };
      static void Main(string[] args)
      {
      }
   }
}
Since this is a simple command line application, let's add some basic argument handling to our main function.

Read more: Switch on code