存储在我的数据库中的密码是这样加密的:
byte[] salt = NewSalt();
string encryptedPassword = EncryptPassword("passwordInTheClear", salt);
// Add/update the admin-user with password and salt.
加密功能:
public static string EncryptPassword(string password, byte[] salt)
{
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
return Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
}
制盐机:
public static byte[] NewSalt()
{
// generate a 128-bit salt using a secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
return salt;
}
[当用户尝试登录系统时,我使用相同的加密功能和相同的盐,从登录表单中加密输入的密码,并将其与数据库中存储的加密密码进行比较:
// (I have separated out the password check from the linq query just for debugging purposes)
AdminUser au = await db.AdminUsers
.Where(u =>
u.Email1 == loginForm.UserName)
.FirstOrDefaultAsync().ConfigureAwait(false);
byte[] salt = Encoding.ASCII.GetBytes(au.PasswordSalt);
string encryptedEnteredPassword = EncryptPassword(loginForm.Password, salt);
if (au.Password == encryptedEnteredPassword)
{
// Success!
}
但是存储的和输入的密码不匹配。
示例:
In the database:
Unencrypted password: 1234
Salt: Cda6ZgNVluChtzseyq9uMQ==
Encrypted password: PKzE3rr9CGGmVW3UJS1N7mqrXmzni3hsqyCtP8lrehE=
In the login form:
Entered, unencrypted password: 1234
Salt: Cda6ZgNVluChtzseyq9uMQ==
Encrypted password: WwYUZqV1GfuRKEitpRdKDjTMEGWy+1nYzpkWI+eZPB0=
您正在以ASCII形式从数据库中获取盐,而示例中的盐显然是Base64。您只需将Encoding.ASCII.GetBytes(au.PasswordSalt)
替换为Convert.FromBase64String(au.PasswordSalt)
并命名为一天。