Created
June 8, 2011 19:45
-
-
Save jptoto/1015209 to your computer and use it in GitHub Desktop.
Encrypting Passwords
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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