36 lines
983 B
C#
36 lines
983 B
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
using Microsoft.Extensions.Options;
|
|
using MxGateway.Server.Configuration;
|
|
|
|
namespace MxGateway.Server.Security.Authentication;
|
|
|
|
public sealed class ApiKeySecretHasher(
|
|
IConfiguration configuration,
|
|
IOptions<GatewayOptions> options) : IApiKeySecretHasher
|
|
{
|
|
public byte[] HashSecret(string secret)
|
|
{
|
|
string pepper = GetPepper();
|
|
byte[] pepperBytes = Encoding.UTF8.GetBytes(pepper);
|
|
byte[] secretBytes = Encoding.UTF8.GetBytes(secret);
|
|
|
|
using HMACSHA256 hmac = new(pepperBytes);
|
|
|
|
return hmac.ComputeHash(secretBytes);
|
|
}
|
|
|
|
private string GetPepper()
|
|
{
|
|
string pepperSecretName = options.Value.Authentication.PepperSecretName;
|
|
string? pepper = configuration[pepperSecretName];
|
|
|
|
if (string.IsNullOrWhiteSpace(pepper))
|
|
{
|
|
throw new ApiKeyPepperUnavailableException(pepperSecretName);
|
|
}
|
|
|
|
return pepper;
|
|
}
|
|
}
|