Hash Passwords in C# and Visual Basic Using SHA-512

We recently covered an easy way to hash passwords using SHA-1 in .NET using either Visual Basic or C#. In most cases, SHA-1 encryption is “secure enough”, but there are some mathematical weaknesses. Microsoft’s .NET platform (specifically the System.Security class) allows you to encrypt passwords with a number of differnet algorithms without having to know the mathematics behind them.

Today, we’re going to encrypt a string with SHA-2, specifically the SHA-512 derivation of SHA-2, which should hypothetically be more secure than SHA-1 because it has a longer message digest than SHA-1. The example code I’m going to show off today also uses a “salt“, whereas the previous function I showed off didn’t. This will make your hashed-passwords more immume to dictionary attacts because not only would the hacker have to develop a hash for every commonly known password, but as well as every commonly known password multiplied by the nearly infinite number of possible salts.

Here’s the function:

    public static string CreateSHAHash(string Password, string Salt)
    {
        System.Security.Cryptography.SHA512Managed HashTool = new System.Security.Cryptography.SHA512Managed();
        Byte[] PasswordAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Password, Salt));
        Byte[] EncryptedBytes = HashTool.ComputeHash(PasswordAsByte);
        HashTool.Clear();
        return Convert.ToBase64String(EncryptedBytes);
    }

How it works:

This method makes use of the System.Security.Cryptography class. It combines your password and the salt that you provide and  turns it into a byte-array. It runs those bytes through the has computation function provided by the class and returns an 88-bit string of the message-digest/hash that’s created.

Comments

  1. Then, if the salt provides entropy and become part of the digest, how can you test the password against the digest?

    Wouldn’t the password that needed to be checked against the digest also require the same salt?

  2. Thinkerly – Yep. You actually keep the salt in a separate non-encrypted record of the database. I think the general idea is to add something to lengthen your string so that (1) it’s harder to crack, and (2) any predefined dictionaries of password-hash combinations would be rendered useless…but I’m not much of a security buff, I could be wrong. :-)

  3. Akin Kenneth says:

    How do i get the original password back?

  4. You cannot. Hashes are a one-way function.

Speak Your Mind

*