February 19, 2014

Encryption and Decryption in .NET

You want to scramble data on the server side before it's saved and also want to retrieve it later and unscramble it.

Encryption and Decryption is what you want.
There are 2 types, Symmetric and Asymmetric.
Symmetric uses 1 key (private) and this same key is used to encrypt and decrypt.
Asymmetric uses 2 keys, 1 for encryption (public) and 1 for decryption (private)

So at least a key is required in all cases. This needs to be stored somewhere. Seems that hardcoded in code or in a config file seems to be the preference.
When storing the key in the web.config ensure that the section is encrypted itself so that it's not human readable http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx.

.NET has a bunch of classes which can be do the actual work, see the
System.Security.Cryptography namespace. See the SymmetricAlgorithm and the AsymmetricAlgorithm classes. Use the (SymmetricAlgorithm)CryptoConfig.CreateFromName(provider)) and get the provider form the web.config with something like ConfigurationManager.AppSettings["encryption"]

You can create create a key with

Additionally you can add Salt to the encryption, the following case basically adds complexity to the key before the encryption takes place. This makes it more difficult for someone to decrypt if they only have the key.
private static string CreateSalt(int size)
            //Generate a cryptographic random number.
            RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
            byte[] buff = new byte[size];
            var asHex = BitConverter.ToString(buff).Replace("-"",0x");
            // Return a Base64 string representation of the random number.
            return Convert.ToBase64String(buff);

The generated key could then be used with some of the .NET code like follows:
private const ushort ITERATIONS = 300;
private static readonly byte[] SALT = new byte[] { 0xBA, 0x72, 0xCA, 0xC6, 0x35, 0xC2, 0x9E, 0xAB, 0x87, 0x0F, 0x58, 0xD4, 0x5F, 0xF0, 0x88, 0x6E, 0xAA, 0x74, 0x9B, 0xE9 };
        private static byte[] CreateKey(string password, int keySize)
            DeriveBytes derivedKey = new Rfc2898DeriveBytes(password, SALT, ITERATIONS);
            return derivedKey.GetBytes(keySize >> 3);
  public static string DoEncrypt(string plainText, string key, string provider)
            using (SymmetricAlgorithm algo = (SymmetricAlgorithmCryptoConfig.CreateFromName(provider))
                var newKey = CreateKey(key, algo.KeySize);
                algo.Key = newKey;
    // BlockSize is in bits.
    algo.IV = new byte[algo.BlockSize / 8];
    using (ICryptoTransform tx = algo.CreateEncryptor())
     byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);
     byte[] cipherBytes = tx.TransformFinalBlock(plainBytes, 0, plainBytes.Length);
     return BytesToHexString(cipherBytes);

No comments: