Created
February 5, 2015 15:52
-
-
Save Deathspike/753c5cae7bc4992b695c to your computer and use it in GitHub Desktop.
C# Password Storage
This file contains hidden or 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
| public class Account | |
| { | |
| #region Abstract | |
| private static string GenerateHash(string password, string salt, int iterations) | |
| { | |
| using (var rfc2898DeriveBytes = new Rfc2898DeriveBytes(password, Convert.FromBase64String(salt), iterations)) | |
| { | |
| return Convert.ToBase64String(rfc2898DeriveBytes.GetBytes(64)); | |
| } | |
| } | |
| private static string GenerateSalt() | |
| { | |
| using (var randomNumberGenerator = RandomNumberGenerator.Create()) | |
| { | |
| var buffer = new byte[32]; | |
| randomNumberGenerator.GetBytes(buffer); | |
| return Convert.ToBase64String(buffer); | |
| } | |
| } | |
| #endregion | |
| #region Methods | |
| public bool IsValid(string password) | |
| { | |
| return Iterations != null && !string.IsNullOrEmpty(Salt) && Hash == GenerateHash(password, Salt, (int)Iterations); | |
| } | |
| public void Update(string password) | |
| { | |
| var random = new Random(); | |
| Salt = GenerateSalt(); | |
| Iterations = random.Next(10000, 20000); | |
| Hash = GenerateHash(password, Salt, (int)Iterations); | |
| } | |
| #endregion | |
| #region Properties | |
| public int? Iterations { get; set; } | |
| public string Hash { get; set; } | |
| public string Salt { get; set; } | |
| #endregion | |
| } |
This file contains hidden or 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
| public class AccountController : Controller | |
| { | |
| public ActionResult ChangePassword(int id, string oldPassword, string newPassword) | |
| { | |
| var account = Context.Accounts.FirstOrDefault(x => x.Id == id); | |
| if (account != null && account.IsValid(oldPassword)) | |
| { | |
| account.Update(newPassword); | |
| return Redirect("/yay"); | |
| } | |
| return Redirect("/nay"); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment