Added hashing algorithm and factory

This commit is contained in:
quentin 2024-07-09 18:03:05 -05:00
parent 8b6bcc7c37
commit ca059ce75d
6 changed files with 72 additions and 1 deletions

View File

@ -0,0 +1,19 @@
using API.Hashing.Interfaces;
using DAL.Models;
namespace API.Hashing
{
public class HashingFactory : IHashingFactory
{
public IHashingAlgorithm? getAlgorithm(HashingType type)
{
switch (type)
{
case HashingType.PBKDF2_SHA512_64_250000:
return new Pbkdf2();
default:
return null;
}
}
}
}

View File

@ -0,0 +1,9 @@
namespace API.Hashing.Interfaces
{
public interface IHashingAlgorithm
{
public string hash(string password, out byte[] salt);
public string hash(string password, byte[] salt);
}
}

View File

@ -0,0 +1,9 @@
using DAL.Models;
namespace API.Hashing.Interfaces
{
public interface IHashingFactory
{
public IHashingAlgorithm? getAlgorithm(HashingType type);
}
}

28
API/Hashing/Pbkdf2.cs Normal file
View File

@ -0,0 +1,28 @@
using API.Hashing.Interfaces;
using System.Security.Cryptography;
using System.Text;
namespace API.Hashing
{
public class Pbkdf2 : IHashingAlgorithm
{
private const int KeySize = 512;
private const int Iterations = 250000;
private readonly HashAlgorithmName _algorithmName = HashAlgorithmName.SHA512;
public string hash(string password, out byte[] salt)
{
salt = RandomNumberGenerator.GetBytes(KeySize);
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, Iterations, _algorithmName, KeySize);
return Convert.ToHexString(hash);
}
public string hash(string password, byte[] salt)
{
byte[] hash = Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, Iterations, _algorithmName, KeySize);
return Convert.ToHexString(hash);
}
}
}

View File

@ -1,5 +1,7 @@
using API.Authentication;
using API.Authentication.Interfaces;
using API.Hashing;
using API.Hashing.Interfaces;
using API.Services;
using DAL.Contexts;
using Microsoft.EntityFrameworkCore;
@ -40,6 +42,10 @@ namespace API
builder.Services.AddTransient<IYesAuthentication, YesAuthentication>();
builder.Services.AddTransient<IColorAuthentication, ColorAuthentication>();
builder.Services.AddTransient<IHashingFactory, HashingFactory>();
builder.Services.AddTransient<IHashingAlgorithm, Pbkdf2>();
WebApplication app = builder.Build();
if (app.Environment.IsDevelopment())

View File

@ -9,7 +9,7 @@ namespace DAL.Models
[JsonConverter(typeof(JsonStringEnumConverter))]
public enum HashingType
{
PBKDF2_SHA512_64_210000
PBKDF2_SHA512_64_250000
}
[Table("users")]