Encryption 101: This Hash Needs Salt

Yesterday, I wrote about how to do simple, one-way encryption using a hash algorithm. This is terrific for encrypting data that doesn’t need to be decrypted, like user passwords. The problem with hash algorithms is that the same values encrypt to the same encrypted values. This is bad because it is possible to see that two encrypted values are the same.

But do not worry. You can turn a hash into a salted hash with one very easy adjustment: add some random bytes to the value. Of course, in order for this to be effective, you’ll also need to store the salt value. When creating the hash for storage, you’ll use salt+value. When creating the hash for comparison, you’ll use salt+value. Get it?

Here’s a short example that uses the RNGCryptoServiceProvider class (RNG = Random Number Generator) to create a salt:

namespace adamprescott.net.EncryptionSaltedHash
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        private void Run()
        {
            Console.Write("Input: ");
            var input = Console.ReadLine();

            var salt = GetSalt();
            var hashed = HashText(salt + input);
            Console.WriteLine("Salt: {0}", salt);
            Console.WriteLine("Hashed: {0}", HashText(input));

            Console.WriteLine();
            Console.Write("What did you just enter?: ");
            input = Console.ReadLine();
            if (string.Equals(hashed, HashText(salt + input)))
            {
                Console.WriteLine("You are an honest person.");
            }
            else
            {
                Console.WriteLine("You are a liar!");
            }

            Console.ReadLine();
        }

        private string HashText(string text)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                var bytes = Encoding.UTF8.GetBytes(text);
                var hash = md5.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }

        private string GetSalt()
        {
            using (var rng = new RNGCryptoServiceProvider())
            {
                var bytes = new byte[8];
                rng.GetBytes(bytes);
                return Convert.ToBase64String(bytes);
            }
        }
    }
}

Encryption 101: Getting Your Hash On

Encryption can be a daunting topic. It’s mostly used only when needed, and it’s typically needed when sensitive data needs to be protected. There are a lot of different ways to encrypt data, and even “encryption made simple” articles can get very complicated. But, like many topics, it’s really not as difficult as it seems.

Part of simplifying the solution lies in identifying your needs. Let’s look at a very easy scenario: encrypting passwords. Obviously, you don’t want to store passwords in plain text. I’ve inherited systems with plain text passwords, and I think it’s flat-out embarrassing. The seemingly obvious solution would be to encrypt a password before saving it and then decrypt it for comparison during the authentication process. That’s over-complicating it, though; what you need is a hash!

Using a hash algorithm is a great way to create one-way encryption. This is ideal for a scenario like passwords. Encrypt the password, and store the encrypted value. When it’s time to authenticate, encrypt the user input and compare. If the encrypted strings match, so do the passwords.

Here’s an easy way to do MD5 encryption in C#:

namespace adamprescott.net.EncryptionHash
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        private void Run()
        {
            Console.Write("Input: ");
            var input = Console.ReadLine();
            Console.WriteLine("Hashed: {0}", HashText(input));
            Console.ReadLine();
        }

        private string HashText(string text)
        {
            using (var md5 = new MD5CryptoServiceProvider())
            {
                var bytes = Encoding.UTF8.GetBytes(text);
                var hash = md5.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
    }
}

Want to use a different hash algorithm? No problem! Just change the CryptoServiceProvider. Here’s the same example using SHA1:

namespace adamprescott.net.EncryptionHash
{
    using System;
    using System.Security.Cryptography;
    using System.Text;

    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Run();
        }

        private void Run()
        {
            Console.Write("Input: ");
            var input = Console.ReadLine();
            Console.WriteLine("Hashed: {0}", HashText(input));
            Console.ReadLine();
        }

        private string HashText(string text)
        {
            using (var sha1 = new SHA1CryptoServiceProvider())
            {
                var bytes = Encoding.UTF8.GetBytes(text);
                var hash = sha1.ComputeHash(bytes);
                return Convert.ToBase64String(hash);
            }
        }
    }
}