Skip to content

Instantly share code, notes, and snippets.

Last active Aug 29, 2015
What would you like to do?
ASP.NET HMACSHA256 Password hashing
/// <summary>
/// Given a password and salt string, along with an algorithm (MVC4 defaults to HMACSHA256), calculates the password's
/// hash value as stored in the DB.
/// </summary>
/// <param name="password">Plaintext password</param>
/// <param name="salt">Base64 string containing user's salt value</param>
/// <param name="hashingAlgorithm">Known .NET crypto algorithm name. Defaults to MVC4's default of HMACSHA256.</param>
/// <returns>Base64-encoded password hash string</returns>
/// <exception cref="CryptographicException">If hashingAlgorithm is unknown to .NET</exception>
private string HashPassword(string password, string salt, string hashingAlgorithm = "HMACSHA256") {
byte[] passwordBytes = Encoding.Unicode.GetBytes(password);
byte[] saltBytes = Convert.FromBase64String(salt);
var saltyPasswordBytes = new byte[saltBytes.Length + passwordBytes.Length];
Buffer.BlockCopy(saltBytes, 0, saltyPasswordBytes, 0, saltBytes.Length);
Buffer.BlockCopy(passwordBytes, 0, saltyPasswordBytes, saltBytes.Length, passwordBytes.Length);
switch (hashingAlgorithm) {
case "HMACSHA256":
return Convert.ToBase64String(new HMACSHA256(saltBytes).ComputeHash(saltyPasswordBytes));
// Supported types include: SHA1, MD5, SHA256, SHA384, SHA512
HashAlgorithm algorithm = HashAlgorithm.Create(hashingAlgorithm);
if (algorithm != null) {
return Convert.ToBase64String(algorithm.ComputeHash(saltyPasswordBytes));
throw new CryptographicException("Unknown hash algorithm");
public string UpdatePasswordSql(string password, string salt, int userId) {
return String.Format("UPDATE my_aspnet_membership SET Password = '{0}', isLockedOut = 0, LastPasswordChangedDate = NOW() WHERE userId = {1};", HashPassword(password, salt), userId);
void Main()
// Run this to get statement to paste below:
// SELECT CONCAT('UpdatePasswordSql("NEW_PASSWORD_HERE", "', passwordKey, '", ', userId, ').Dump();'), userId, email from my_aspnet_membership where email like '%somer%';
UpdatePasswordSql("NEW_PASSWORD_HERE", "USER_SALT", USER_ID).Dump();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment