Skip to content

Instantly share code, notes, and snippets.

@mbalex99
Created June 7, 2013 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mbalex99/5730078 to your computer and use it in GitHub Desktop.
Save mbalex99/5730078 to your computer and use it in GitHub Desktop.
Salted Hash Password
public static class SaltedHash
{
public static byte[] GenerateSalt()
{
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
int minSaltSize = 16;
int maxSaltSize = 32;
Random random = new Random();
int saltSize = random.Next(minSaltSize, maxSaltSize);
byte[] byteArray = new byte[saltSize];
rng.GetBytes(byteArray);
return byteArray;
}
public static byte[] GenerateSaltedHash(string passwordPlainText, byte[] saltBytes)
{
byte[] clearTextBytes = Encoding.UTF8.GetBytes(passwordPlainText);
byte[] clearTextWithSaltBytes = new byte[clearTextBytes.Length + saltBytes.Length];
for (int i = 0; i < clearTextBytes.Length; i++)
{
clearTextWithSaltBytes[i] = clearTextBytes[i];
}
for (int i = 0; i < saltBytes.Length; i++)
{
clearTextWithSaltBytes[clearTextBytes.Length + i] = saltBytes[i];
}
//Calculate the hash
HashAlgorithm hash = new SHA256Managed();
byte[] hashBytes = hash.ComputeHash(clearTextWithSaltBytes);
return hashBytes;
}
public static bool IsPasswordValid(string passwordPlainText, byte[] savedSaltBytes, byte[] savedHashBytes)
{
byte[] array1 = GenerateSaltedHash(passwordPlainText, savedSaltBytes);
byte[] array2 = savedHashBytes;
if (array1.Length != array2.Length)
return false;
for(int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment