我在我的网站上使用SHA1来记录密码。我试图转向ASP.NET身份。我找到了如何验证旧密码(ASP.NET Identity default Password Hasher, how does it work and is it secure?):
public class CustomPasswordHasher : IPasswordHasher
{
//....
public static bool VerifyHashedPassword(string hashedPassword, string password)
{
byte[] buffer4;
if (hashedPassword == null)
{
return false;
}
if (password == null)
{
throw new ArgumentNullException("password");
}
// Old hash verification
using (SHA1Managed sha1 = new SHA1Managed())
{
var hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(password));
var sb = new StringBuilder(hash.Length * 2);
foreach (byte b in hash)
{
sb.Append(b.ToString("x2"));
}
if(hashedPassword == sb.ToString()) return true;
else return false;
}
// Identity hash verification
byte[] src = Convert.FromBase64String(hashedPassword);
if ((src.Length != 0x31) || (src[0] != 0))
{
return false;
}
byte[] dst = new byte[0x10];
Buffer.BlockCopy(src, 1, dst, 0, 0x10);
byte[] buffer3 = new byte[0x20];
Buffer.BlockCopy(src, 0x11, buffer3, 0, 0x20);
using (Rfc2898DeriveBytes bytes = new Rfc2898DeriveBytes(password, dst, 0x3e8))
{
buffer4 = bytes.GetBytes(0x20);
}
return ByteArraysEqual(buffer3, buffer4);
}
//....
}
在我的自定义ApplicationUserManager中,我设置了PasswordHasher属性:
//....
manager.PasswordHasher = new CustomPasswordHasher();
//....
现在,我想删除旧的哈希(sha1)并保存新的哈希。我能做到吗?
提前致谢!
答案 0 :(得分:4)
在用户尝试登录之前,您无法执行此操作 - 您只有SHA1哈希值。从SHA1,您无法转换为其他哈希算法。
但是当用户登录时,你的密码在内存中并且可以使用它来生成新的哈希。这里有一些伪代码:
public void Login(String username, String password)
{
if(DoesOldHashMatch(username, password)){
var newHash = NewHasher.GetPasswordHash(password);
UpdateUserPasswordHash(username, newHash);
SetLoginCookie(username);
return;
}
if(NewHashMatch(username, password))
{
SetLoginCookie(username);
}
}