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.