Код: Выделить всё
UserName: VARCHAR(50)
PasswodsHashed: VARBINARY
PasswordSalted: VARBIANRY
< /code>
Эта таблица имеет тысячи записей, в которых пароль ранее был хэширован с использованием SHA512 с помощью хранимой процедуры. Я хочу отодвинуть логику от использования хранимой процедуры в мой веб -API ASP.NET Core 9.public class User // (SQL Server user table representation)
{
public string Username { get; set; } = null!;
public byte PasswordHashed { get; set; } // Should this be a BinaryData type?
public byte SaltHashed { get; set; }
}
public class UserLoginRequest
{
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
}
public class UserLoginResponse
{
public User UserDetails { get; set; } = null!;
public string Token { get; set; } = null!;
}
Код: Выделить всё
public static class SecretHasher
{
private const int _saltSize = 16; // 128 bits
private const int _keySize = 32; // 256 bits
private const int _iterations = 50000;
private static readonly HashAlgorithmName _algorithm = HashAlgorithmName.SHA256;
private const char segmentDelimiter = ':';
public static string Hash(string input)
{
byte[] salt = RandomNumberGenerator.GetBytes(_saltSize);
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(
input,
salt,
_iterations,
_algorithm,
_keySize
);
return string.Join(
segmentDelimiter,
Convert.ToHexString(hash),
Convert.ToHexString(salt),
_iterations,
_algorithm
);
}
public static bool Verify(string input, string hashString)
{
string[] segments = hashString.Split(segmentDelimiter);
byte[] hash = Convert.FromHexString(segments[0]);
byte[] salt = Convert.FromHexString(segments[1]);
int iterations = int.Parse(segments[2]);
HashAlgorithmName algorithm = new HashAlgorithmName(segments[3]);
byte[] inputHash = Rfc2898DeriveBytes.Pbkdf2(
input,
salt,
iterations,
algorithm,
hash.Length
);
return CryptographicOperations.FixedTimeEquals(inputHash, hash);
}
}
метод Secrethasher :
Code> Метод Secrethasher :
Code> Method в классе Secrethasher :
.public async Task Login(UserLoginRequest logindetails)
{
// Fetch the stored hash password and hash salt
var user = _context.TestUsers.FirstOrDefault(u => u.Username.ToLower() == logindetails.Username.ToLower());
// I am having problems in the conversion on the next line from byte to string and I have tried several different ways using cast, ToString() etc etc..
// I also need to concatenate PasswordHashed & SaltHashed to pass to the Verify method as a single input(?) ***
var passwordHash = (byte)user.PasswordHashed; // + byte (byte)user.SaltHashed;
string hashed = SecretHasher.Hash(passwordSalt.ToString());
bool isPasswordCorrect = SecretHasher.Verify(logindetails.Password, passwordSalt.ToString());
Console.WriteLine("isPasswordCorrect= " + isPasswordCorrect);
// etc etc...
}
< /code>
Обычная ошибка, которую я получаю, < /p>
не может преобразовать System.byte в байт (с удаленной конкатенацией.>
Подробнее здесь: https://stackoverflow.com/questions/797 ... ing-for-as
Мобильная версия