Skip to content

Instantly share code, notes, and snippets.

@jptoto
Created June 8, 2011 19:45
Show Gist options
  • Save jptoto/1015209 to your computer and use it in GitHub Desktop.
Save jptoto/1015209 to your computer and use it in GitHub Desktop.
Encrypting Passwords
[HttpPost]
public ActionResult Logon(LoginUserViewModel loginUser)
{
if (!ModelState.IsValid)
return View(loginUser);
User user = userRepository.GetUser(loginUser.UserName);
if (user != null)
{
string hashedPassword = EncryptionHelper.Encrypt(user.Salt, loginUser.Password);
if (user.Password == hashedPassword )
{
SignUserIn(user);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password are incorrect.");
}
}
else
{
ModelState.AddModelError("", "The user name or password are incorrect.");
}
return View(loginUser);
}
using System.Security.Cryptography;
using System.Text;
namespace Web.Helpers
{
public static class EncryptionHelper
{
public static string Encrypt(byte[] salt, string password)
{
byte[] passwordBytes = new byte[Encoding.UTF8.GetByteCount(password) + salt.Length]; // Create buffer for password bytes and hash
int passwordLength = Encoding.UTF8.GetBytes(password, 0, password.Length, passwordBytes, 0);
salt.CopyTo(passwordBytes, passwordLength);
byte[] hash = null;
using (SHA512Managed hasher = new SHA512Managed())
{
hash = hasher.ComputeHash(passwordBytes);
}
System.Text.Encoding enc = System.Text.Encoding.ASCII;
return enc.GetString(hash);
}
}
} }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment