Skip to content

Instantly share code, notes, and snippets.

@Deathspike
Created February 5, 2015 15:52
Show Gist options
  • Select an option

  • Save Deathspike/753c5cae7bc4992b695c to your computer and use it in GitHub Desktop.

Select an option

Save Deathspike/753c5cae7bc4992b695c to your computer and use it in GitHub Desktop.
C# Password Storage
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
}
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