Skip to content
Snippets Groups Projects
Commit 26a9cb7e authored by Jakub Konvička's avatar Jakub Konvička
Browse files

refactor: Change hashing to BCrypt algo.

parent 25854d5b
1 merge request!10Merge: Release version 1.1
using System.Security.Cryptography;
namespace WebAPI.Utils
{
public static class PasswordHasher
{
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 = GenerateRandomBytes(SaltSize);
byte[] hash = DeriveKey(input, salt, Iterations, Algorithm, KeySize);
return string.Join(
SegmentDelimiter,
Convert.ToHexString(hash),
Convert.ToHexString(salt),
Iterations,
Algorithm
);
return BCrypt.Net.BCrypt.HashPassword(input, 12);
}
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 = DeriveKey(input, salt, iterations, algorithm, hash.Length);
return CryptographicOperations.FixedTimeEquals(inputHash, hash);
}
private static byte[] GenerateRandomBytes(int size)
{
byte[] randomBytes = new byte[size];
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
{
rng.GetBytes(randomBytes);
}
return randomBytes;
return BCrypt.Net.BCrypt.Verify(input, hashString);
}
private static byte[] DeriveKey(string input, byte[] salt, int iterations, HashAlgorithmName algorithm, int keySize)
{
using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(input, salt, iterations, algorithm))
{
return pbkdf2.GetBytes(keySize);
}
}
}
}
......@@ -8,6 +8,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.9"/>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0"/>
</ItemGroup>
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment