我无法登录用户,因为密码哈希值不匹配。我做错了什么。我的sql服务器保存的密码哈希值数据类型是nvarchar。我之前使用了二进制数据类型,但没有成功。
private readonly MovieHubContext _context;
public AuthRepository(MovieHubContext context)
{
_context = context;
}
//method is called when the user hits the login button
public async Task<Users> Login(string username, string password)
{
//returns the username from the databse
var user = await _context.Users.FirstOrDefaultAsync(x => x.UserName == username);
if (user == null)
{
return null;
}
if (!VerifyPasswordHash(password, System.Text.Encoding.UTF8.GetBytes(user.PasswordHash),
System.Text.Encoding.UTF8.GetBytes(user.PasswordSalt)))
return null;
return user;
}
// this method is used to verify the password
private bool VerifyPasswordHash(string password, byte[] passwordHash, byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512(passwordSalt))
{
//changes the string into byte and them computes the hash
byte[] computedHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
for (int i = 0; i < computedHash.Length; i++)
{
//compares the hashed password(user input) with the hashed password from the database
if (computedHash[i] != passwordHash[i])
return false;
}
}
return true;
}
// This method is used to register the users
public async Task<Users> Register(Users users, string password)
{
byte[] passwordHash, passwordSalt;
CreatePasswordHash(password, out passwordHash, out passwordSalt);
users.PasswordHash = System.Text.Encoding.UTF8.GetString(passwordHash);
users.PasswordSalt = System.Text.Encoding.UTF8.GetString(passwordSalt);
//save into database
await _context.Users.AddAsync(users);
await _context.SaveChangesAsync();
return users;
}
private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
{
using (var hmac = new System.Security.Cryptography.HMACSHA512())
{
passwordSalt = hmac.Key;
passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
}
}
public async Task<bool> UserExists(string username)
{
if (await _context.Users.AnyAsync(x => x.UserName == username))
return true;
return false;
}
这是我编写的用于注册和登录客户端的代码。我找不到错在哪里。