mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 00:11:10 +00:00
Updates to .NET 9.0
This commit is contained in:
commit
acbdb0a5f8
853 files changed
+34993
-10123
No files matched your search
+17
-1
@@ -1,6 +1,13 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Infrastructure.Core.Authentication;
|
||||
using Lumina.Infrastructure.Core.Security;
|
||||
using Lumina.Infrastructure.Core.Time;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
|
||||
@@ -9,6 +16,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection;
|
||||
/// <summary>
|
||||
/// Contains all services of the Infrastructure layer.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class InfrastructureLayerServices
|
||||
{
|
||||
/// <summary>
|
||||
@@ -21,6 +29,14 @@ public static class InfrastructureLayerServices
|
||||
// scan the current assembly for validators and add them to the DI container
|
||||
services.AddValidatorsFromAssembly(Assembly.GetExecutingAssembly(), ServiceLifetime.Singleton);
|
||||
|
||||
services.AddSingleton<IHashService, HashService>();
|
||||
services.AddSingleton<ICryptographyService, CryptographyService>();
|
||||
services.AddSingleton<IJwtTokenGenerator, JwtTokenGenerator>();
|
||||
services.AddSingleton<IQRCodeGenerator, QRCodeGenerator>();
|
||||
services.AddSingleton<ITokenGenerator, TokenGenerator>();
|
||||
services.AddSingleton<ITotpTokenGenerator, TotpTokenGenerator>();
|
||||
services.AddSingleton<IDateTimeProvider, DateTimeProvider>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Lumina.Infrastructure.Common.Utilities;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
#endregion
|
||||
@@ -12,6 +13,7 @@ namespace Lumina.Infrastructure.Common.DependencyInjection;
|
||||
/// <summary>
|
||||
/// Class containing the shared configuration bindings of the application.
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public static class SharedConfiguration
|
||||
{
|
||||
/// <summary>
|
||||
@@ -42,6 +44,22 @@ public static class SharedConfiguration
|
||||
.Bind(configuration.GetRequiredSection(DatabaseSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<MediaSettingsModel>()
|
||||
.Bind(configuration.GetRequiredSection(MediaSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<JwtSettingsModel>()
|
||||
.Bind(configuration.GetRequiredSection(JwtSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
services.AddOptions<EncryptionSettingsModel>()
|
||||
.Bind(configuration.GetRequiredSection(EncryptionSettingsModel.SECTION_NAME))
|
||||
.ValidateFluently()
|
||||
.ValidateOnStart();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,15 @@ public static partial class Errors
|
||||
{
|
||||
public static class Configuration
|
||||
{
|
||||
public static Error ApplicationThemeCannotBeEmpty => Error.Validation(nameof(ApplicationThemeCannotBeEmpty));
|
||||
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(nameof(DatabaseConnectionStringCannotBeEmpty));
|
||||
public static Error ApplicationThemeCannotBeEmpty => Error.Validation(description: nameof(ApplicationThemeCannotBeEmpty));
|
||||
public static Error DatabaseConnectionStringCannotBeEmpty => Error.Validation(description: nameof(DatabaseConnectionStringCannotBeEmpty));
|
||||
public static Error MediaRootDirectoryCannotBeEmpty => Error.Validation(description: nameof(MediaRootDirectoryCannotBeEmpty));
|
||||
public static Error EncryptionSecretKeyCannotBeEmpty => Error.Validation(description: nameof(EncryptionSecretKeyCannotBeEmpty));
|
||||
public static Error EncryptionSecretKeyMustBeABase64String => Error.Validation(description: nameof(EncryptionSecretKeyMustBeABase64String));
|
||||
public static Error JwtSecretKeyCannotBeEmpty => Error.Validation(description: nameof(JwtSecretKeyCannotBeEmpty));
|
||||
public static Error JwtSecretKeyTooShort => Error.Validation(description: nameof(JwtSecretKeyTooShort));
|
||||
public static Error JwtExpiryMinutesMustBePositive => Error.Validation(description: nameof(JwtExpiryMinutesMustBePositive));
|
||||
public static Error JwtIssuerCannotBeEmpty => Error.Validation(description: nameof(JwtIssuerCannotBeEmpty));
|
||||
public static Error JwtAudienceCannotBeEmpty => Error.Validation(description: nameof(JwtAudienceCannotBeEmpty));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Models.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Model for deserializing media settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class EncryptionSettingsModel
|
||||
{
|
||||
public const string SECTION_NAME = "EncryptionSettings";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the root directory where media files are stored.
|
||||
/// </summary>
|
||||
public required string SecretKey { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Models.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Model for deserializing media settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class JwtSettingsModel
|
||||
{
|
||||
public const string SECTION_NAME = "JwtSettings";
|
||||
|
||||
/// <summary>
|
||||
/// The secret key used to sign the JWT. This should be a strong, securely stored key.
|
||||
/// </summary>
|
||||
public required string SecretKey { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The duration (in minutes) for which the JWT is valid.
|
||||
/// </summary>
|
||||
public required int ExpiryMinutes { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The issuer of the JWT, typically the application or service generating the token.
|
||||
/// </summary>
|
||||
public required string Issuer { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// The intended audience for the JWT, usually representing the clients that can consume the token.
|
||||
/// </summary>
|
||||
public required string Audience { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using System.Diagnostics;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Models.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Model for deserializing media settings.
|
||||
/// </summary>
|
||||
[DebuggerDisplay("{SECTION_NAME}")]
|
||||
public class MediaSettingsModel
|
||||
{
|
||||
public const string SECTION_NAME = "MediaSettings";
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets the root directory where media files are stored.
|
||||
/// </summary>
|
||||
public required string RootDirectory { get; init; }
|
||||
}
|
||||
@@ -15,6 +15,6 @@ public class CommonSettingsModelValidator : AbstractValidator<CommonSettingsMode
|
||||
/// </summary>
|
||||
public CommonSettingsModelValidator()
|
||||
{
|
||||
RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Code);
|
||||
RuleFor(x => x.Theme).NotEmpty().WithMessage(Errors.Errors.Configuration.ApplicationThemeCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,6 @@ public class DatabaseSettingsModelValidator : AbstractValidator<DatabaseSettings
|
||||
/// </summary>
|
||||
public DatabaseSettingsModelValidator()
|
||||
{
|
||||
RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Code);
|
||||
RuleFor(x => x.DefaultConnection).NotEmpty().WithMessage(Errors.Errors.Configuration.DatabaseConnectionStringCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using System;
|
||||
using System.Buffers.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for the EncryptionSettings application configuration settings section.
|
||||
/// </summary>
|
||||
public class EncryptionSettingsModelValidator : AbstractValidator<EncryptionSettingsModel>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="EncryptionSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
public EncryptionSettingsModelValidator()
|
||||
{
|
||||
RuleFor(x => x.SecretKey)
|
||||
.NotEmpty().WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyCannotBeEmpty.Description)
|
||||
.Must(value => Base64.IsValid(value.AsSpan())).WithMessage(Errors.Errors.Configuration.EncryptionSecretKeyMustBeABase64String.Description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for the JwtSettings application configuration settings section.
|
||||
/// </summary>
|
||||
public class JwtSettingsModelValidator : AbstractValidator<JwtSettingsModel>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
public JwtSettingsModelValidator()
|
||||
{
|
||||
RuleFor(x => x.SecretKey)
|
||||
.NotEmpty()
|
||||
.WithMessage(Errors.Errors.Configuration.JwtSecretKeyCannotBeEmpty.Description)
|
||||
.MinimumLength(32)
|
||||
.WithMessage(Errors.Errors.Configuration.JwtSecretKeyTooShort.Description);
|
||||
|
||||
RuleFor(x => x.ExpiryMinutes)
|
||||
.GreaterThan(0)
|
||||
.WithMessage(Errors.Errors.Configuration.JwtExpiryMinutesMustBePositive.Description);
|
||||
|
||||
RuleFor(x => x.Issuer)
|
||||
.NotEmpty()
|
||||
.WithMessage(Errors.Errors.Configuration.JwtIssuerCannotBeEmpty.Description);
|
||||
|
||||
RuleFor(x => x.Audience)
|
||||
.NotEmpty()
|
||||
.WithMessage(Errors.Errors.Configuration.JwtAudienceCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using FluentValidation;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Common.Validators;
|
||||
|
||||
/// <summary>
|
||||
/// Validates the needed validation rules for the MediaSettings application configuration settings section.
|
||||
/// </summary>
|
||||
public class MediaSettingsModelValidator : AbstractValidator<MediaSettingsModel>
|
||||
{
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="MediaSettingsModelValidator"/> class.
|
||||
/// </summary>
|
||||
public MediaSettingsModelValidator()
|
||||
{
|
||||
RuleFor(x => x.RootDirectory).NotEmpty().WithMessage(Errors.Errors.Configuration.MediaRootDirectoryCannotBeEmpty.Description);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Class for generating JWT tokens.
|
||||
/// </summary>
|
||||
public class JwtTokenGenerator : IJwtTokenGenerator
|
||||
{
|
||||
private readonly IDateTimeProvider _dateTimeProvider;
|
||||
private readonly JwtSettingsModel _jwtSettingsModel;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="JwtTokenGenerator"/> class.
|
||||
/// </summary>
|
||||
/// <param name="dateTimeProvider">Injected service for time related functionality.</param>
|
||||
/// <param name="jwtSettingsModelOptions">Injected service for retrieving <see cref="JwtSettingsModel"/>.</param>
|
||||
public JwtTokenGenerator(IDateTimeProvider dateTimeProvider, IOptions<JwtSettingsModel> jwtSettingsModelOptions)
|
||||
{
|
||||
_dateTimeProvider = dateTimeProvider;
|
||||
_jwtSettingsModel = jwtSettingsModelOptions.Value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Generates a new JWT token.
|
||||
/// </summary>
|
||||
/// <param name="id">The id of the user for which to generate the token.</param>
|
||||
/// <param name="username">The username of the user for which to generate the token.</param>
|
||||
/// <returns>The generated JWT token.</returns>
|
||||
public string GenerateToken(string id, string username)
|
||||
{
|
||||
// use a symmetric key approach
|
||||
SigningCredentials signingCredentials = new(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettingsModel.SecretKey)), SecurityAlgorithms.HmacSha256);
|
||||
Claim[] claims =
|
||||
[
|
||||
new Claim(JwtRegisteredClaimNames.Sub, id),
|
||||
new Claim(JwtRegisteredClaimNames.UniqueName, username),
|
||||
new Claim(JwtRegisteredClaimNames.Jti, id.ToString())
|
||||
];
|
||||
JwtSecurityToken securityToken = new(
|
||||
issuer: _jwtSettingsModel.Issuer,
|
||||
audience: _jwtSettingsModel.Audience,
|
||||
expires: _dateTimeProvider.UtcNow.AddMinutes(_jwtSettingsModel.ExpiryMinutes),
|
||||
claims: claims,
|
||||
signingCredentials: signingCredentials);
|
||||
return new JwtSecurityTokenHandler().WriteToken(securityToken);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using OtpNet;
|
||||
using QRCoder;
|
||||
using System;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Service for generating QR codes for TOTP.
|
||||
/// </summary>
|
||||
public class QRCodeGenerator : IQRCodeGenerator
|
||||
{
|
||||
private const string ISSUER = "Lumina";
|
||||
|
||||
/// <summary>
|
||||
/// Generates a QR code Data URI for the specified TOTP secret.
|
||||
/// </summary>
|
||||
/// <param name="username">User's username or unique identifier.</param>
|
||||
/// <param name="secret">The TOTP secret for which the QR code should be generated.</param>
|
||||
/// <returns>Data URI for the QR code.</returns>
|
||||
public string GenerateQrCodeDataUri(string username, byte[] secret)
|
||||
{
|
||||
// convert secret to Base32
|
||||
string base32Secret = Base32Encoding.ToString(secret);
|
||||
// build the otpauth URI
|
||||
string otpauthString = $"otpauth://totp/{ISSUER}:{Uri.EscapeDataString(username)}?secret={base32Secret}&issuer={ISSUER}";
|
||||
// generate QR Code
|
||||
QRCoder.QRCodeGenerator qrGenerator = new();
|
||||
QRCodeData qrData = qrGenerator.CreateQrCode(otpauthString, QRCoder.QRCodeGenerator.ECCLevel.Q);
|
||||
PngByteQRCode qrCode = new(qrData);
|
||||
// convert QR Code to Data URI
|
||||
byte[] pngBytes = qrCode.GetGraphic(20); // specify a pixel size if needed
|
||||
string dataUri = "data:image/png;base64," + Convert.ToBase64String(pngBytes);
|
||||
return dataUri;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Service for the service for generating secure tokens for accounts confirmation or recovery.
|
||||
/// </summary>
|
||||
public class TokenGenerator : ITokenGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a secure token.
|
||||
/// </summary>
|
||||
/// <returns>A secure token.</returns>
|
||||
public string GenerateToken()
|
||||
{
|
||||
// allocate an array for the token data
|
||||
byte[] tokenData = new byte[32];
|
||||
// fill the array with a cryptographically strong sequence of random values
|
||||
RandomNumberGenerator.Fill(tokenData);
|
||||
// convert to a Base64 string, but replace URL-unsafe characters '+' and '/' with '-' and '_', and remove padding characters ('=')
|
||||
return Convert.ToBase64String(tokenData).Replace('+', '-').Replace('/', '_').TrimEnd('=');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Authentication;
|
||||
using OtpNet;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Authentication;
|
||||
|
||||
/// <summary>
|
||||
/// Service for generating and validating TOTP tokens.
|
||||
/// </summary>
|
||||
public class TotpTokenGenerator : ITotpTokenGenerator
|
||||
{
|
||||
/// <summary>
|
||||
/// Generates a new TOTP secret for a user.
|
||||
/// </summary>
|
||||
/// <returns>The generated TOTP secret.</returns>
|
||||
public byte[] GenerateSecret()
|
||||
{
|
||||
return KeyGeneration.GenerateRandomKey(); // generate a random key for TOTP
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Validates a TOTP token against the stored secret.
|
||||
/// </summary>
|
||||
/// <param name="secret">The user's TOTP secret.</param>
|
||||
/// <param name="token">The token to validate.</param>
|
||||
/// <returns><see langword="true"/> if valid, <see langword="false"/> otherwise.</returns>
|
||||
public bool ValidateToken(byte[] secret, string token)
|
||||
{
|
||||
Totp totp = new(secret);
|
||||
// verify the TOTP token, allowing for slight time drifts between server and client
|
||||
return totp.VerifyTotp(token, out _, VerificationWindow.RfcSpecifiedNetworkDelay);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using Lumina.Infrastructure.Common.Models.Configuration;
|
||||
using Microsoft.Extensions.Options;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Service for cryptographic concerns.
|
||||
/// </summary>
|
||||
public sealed class CryptographyService : ICryptographyService, IDisposable
|
||||
{
|
||||
private readonly byte[] _key;
|
||||
|
||||
/// <summary>
|
||||
/// Initializes a new instance of the <see cref="CryptographyService"/> class.
|
||||
/// </summary>
|
||||
/// <param name="encryptionSettingsModelOptions">Injected service for retrieving <see cref="EncryptionSettingsModel"/>.</param>
|
||||
public CryptographyService(IOptions<EncryptionSettingsModel> encryptionSettingsModelOptions)
|
||||
{
|
||||
_key = Convert.FromBase64String(encryptionSettingsModelOptions.Value.SecretKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Encrypts a plaintext string using AES encryption with a randomly generated initialization vector (IV).
|
||||
/// </summary>
|
||||
/// <param name="plaintext">The plaintext string to encrypt.</param>
|
||||
/// <returns>A Base64-encoded string of the combined IV and encrypted ciphertext.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="plaintext"/> is <see langword="null"/> or empty.</exception>
|
||||
public string Encrypt(string plaintext)
|
||||
{
|
||||
if (string.IsNullOrEmpty(plaintext))
|
||||
throw new ArgumentException("Value cannot be null or empty", nameof(plaintext));
|
||||
|
||||
// generate a new, random 16-byte IV for each encryption to ensure unique ciphertexts
|
||||
byte[] iv = new byte[16];
|
||||
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
|
||||
rng.GetBytes(iv);
|
||||
|
||||
using Aes aes = Aes.Create();
|
||||
aes.Key = _key;
|
||||
aes.IV = iv;
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
|
||||
using ICryptoTransform encryptor = aes.CreateEncryptor();
|
||||
byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
|
||||
byte[] ciphertext = encryptor.TransformFinalBlock(plaintextBytes, 0, plaintextBytes.Length);
|
||||
|
||||
// combine IV and ciphertext
|
||||
byte[] combined = new byte[iv.Length + ciphertext.Length];
|
||||
Buffer.BlockCopy(iv, 0, combined, 0, iv.Length);
|
||||
Buffer.BlockCopy(ciphertext, 0, combined, iv.Length, ciphertext.Length);
|
||||
|
||||
return Convert.ToBase64String(combined);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Decrypts a Base64-encoded string that contains both the IV and ciphertext.
|
||||
/// </summary>
|
||||
/// <param name="ciphertext">The Base64-encoded string containing both IV and ciphertext.</param>
|
||||
/// <returns>The decrypted plaintext string.</returns>
|
||||
/// <exception cref="ArgumentException">Thrown when <paramref name="ciphertext"/> is <see langword="null"/>, empty, or invalid.</exception>
|
||||
public string Decrypt(string ciphertext)
|
||||
{
|
||||
if (string.IsNullOrEmpty(ciphertext))
|
||||
throw new ArgumentException("Value cannot be null or empty", nameof(ciphertext));
|
||||
|
||||
// decode the combined data (IV + ciphertext) from Base64
|
||||
byte[] combined = Convert.FromBase64String(ciphertext);
|
||||
|
||||
if (combined.Length < 16)
|
||||
throw new ArgumentException("Invalid ciphertext");
|
||||
|
||||
// extract IV and ciphertext
|
||||
byte[] iv = new byte[16];
|
||||
byte[] encryptedData = new byte[combined.Length - 16];
|
||||
Buffer.BlockCopy(combined, 0, iv, 0, 16);
|
||||
Buffer.BlockCopy(combined, 16, encryptedData, 0, encryptedData.Length);
|
||||
|
||||
using Aes aes = Aes.Create();
|
||||
aes.Key = _key;
|
||||
aes.IV = iv;
|
||||
aes.Mode = CipherMode.CBC;
|
||||
aes.Padding = PaddingMode.PKCS7;
|
||||
|
||||
using ICryptoTransform decryptor = aes.CreateDecryptor();
|
||||
byte[] decrypted = decryptor.TransformFinalBlock(encryptedData, 0, encryptedData.Length);
|
||||
return Encoding.UTF8.GetString(decrypted);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clears sensitive key data when the service is disposed.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
Array.Clear(_key, 0, _key.Length);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Konscious.Security.Cryptography;
|
||||
using Lumina.Application.Common.Infrastructure.Security;
|
||||
using System;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Security;
|
||||
|
||||
/// <summary>
|
||||
/// Service for hashing passwords.
|
||||
/// </summary>
|
||||
public sealed class HashService : IHashService
|
||||
{
|
||||
// OWASP recommended parameters for Argon2id
|
||||
private const int MEMORY_SIZE = 19456; // 19 MiB (19 * 1024 = 19456)
|
||||
private const int ITERATIONS = 2;
|
||||
private const int DEGREE_OF_PARALLELISM = 1;
|
||||
private const int HASH_SIZE = 32; // 256 bits
|
||||
private const int SALT_SIZE = 16; // 128 bits
|
||||
|
||||
/// <summary>
|
||||
/// Creates a hash from a string.
|
||||
/// </summary>
|
||||
/// <param name="password">The string to be hashed.</param>
|
||||
/// <returns>The hashed string.</returns>
|
||||
public string HashString(string password)
|
||||
{
|
||||
byte[] salt = new byte[SALT_SIZE];
|
||||
using (RandomNumberGenerator rng = RandomNumberGenerator.Create())
|
||||
rng.GetBytes(salt); // generate a random salt
|
||||
|
||||
byte[] hashBytes;
|
||||
using (Argon2id hasher = new(Encoding.UTF8.GetBytes(password)))
|
||||
{
|
||||
hasher.Salt = salt;
|
||||
hasher.DegreeOfParallelism = DEGREE_OF_PARALLELISM;
|
||||
hasher.MemorySize = MEMORY_SIZE;
|
||||
hasher.Iterations = ITERATIONS;
|
||||
hashBytes = hasher.GetBytes(HASH_SIZE);
|
||||
}
|
||||
// concatenate salt and hash and return as a Base64 string
|
||||
byte[] hashWithSaltBytes = new byte[SALT_SIZE + HASH_SIZE];
|
||||
Buffer.BlockCopy(salt, 0, hashWithSaltBytes, 0, SALT_SIZE);
|
||||
Buffer.BlockCopy(hashBytes, 0, hashWithSaltBytes, SALT_SIZE, HASH_SIZE);
|
||||
return Convert.ToBase64String(hashWithSaltBytes);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies a password against a hash.
|
||||
/// </summary>
|
||||
/// <param name="password">The string to be checked.</param>
|
||||
/// <param name="hashedPassword">The hashed representation of the string to be checked.</param>
|
||||
/// <returns><see langword="true"/> if <paramref name="password"/> and the de-hashed versions of <paramref name="hashedPassword"/> are equal, <see langword="false"/> otherwise.</returns>
|
||||
public bool CheckStringAgainstHash(string password, string hashedPassword)
|
||||
{
|
||||
// convert the Base64 string back into a byte array
|
||||
byte[] hashWithSaltBytes = Convert.FromBase64String(hashedPassword);
|
||||
// validate the length too
|
||||
if (hashWithSaltBytes.Length != SALT_SIZE + HASH_SIZE)
|
||||
return false;
|
||||
|
||||
byte[] saltBytes = new byte[SALT_SIZE];
|
||||
Buffer.BlockCopy(hashWithSaltBytes, 0, saltBytes, 0, SALT_SIZE);
|
||||
|
||||
byte[] hashBytes;
|
||||
using (Argon2id hasher = new(Encoding.UTF8.GetBytes(password)))
|
||||
{
|
||||
hasher.Salt = saltBytes;
|
||||
hasher.DegreeOfParallelism = DEGREE_OF_PARALLELISM;
|
||||
hasher.MemorySize = MEMORY_SIZE;
|
||||
hasher.Iterations = ITERATIONS;
|
||||
hashBytes = hasher.GetBytes(HASH_SIZE);
|
||||
}
|
||||
// get the stored hash from the stored hashed password
|
||||
byte[] storedHashBytes = new byte[HASH_SIZE];
|
||||
Buffer.BlockCopy(hashWithSaltBytes, SALT_SIZE, storedHashBytes, 0, HASH_SIZE);
|
||||
// use constant-time comparison to prevent timing attacks
|
||||
return CryptographicOperations.FixedTimeEquals(hashBytes, storedHashBytes);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#region ========================================================================= USING =====================================================================================
|
||||
using Lumina.Application.Common.Infrastructure.Time;
|
||||
using System;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
#endregion
|
||||
|
||||
namespace Lumina.Infrastructure.Core.Time;
|
||||
|
||||
/// <summary>
|
||||
/// Service for time related concerns
|
||||
/// </summary>
|
||||
[ExcludeFromCodeCoverage]
|
||||
public class DateTimeProvider : IDateTimeProvider
|
||||
{
|
||||
/// <summary>
|
||||
/// The current UTC time.
|
||||
/// </summary>
|
||||
public DateTime UtcNow => DateTime.UtcNow;
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
<TargetFramework>net9.0</TargetFramework>
|
||||
<ImplicitUsings>disable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\server\</BaseOutputPath>
|
||||
<BaseOutputPath>$(SolutionDir)..\bin\api\</BaseOutputPath>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<WarningsNotAsErrors>$(WarningsNotAsErrors);NU1901;NU1902;NU1903;NU1904</WarningsNotAsErrors>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -14,18 +15,22 @@
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="FluentValidation" Version="11.10.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0-rc.2.24473.5" />
|
||||
<PackageReference Include="Konscious.Security.Cryptography.Argon2" Version="1.3.1" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="9.0.0" />
|
||||
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="9.0.0" />
|
||||
<PackageReference Include="Otp.NET" Version="1.4.0" />
|
||||
<PackageReference Include="QRCoder" Version="1.6.0" />
|
||||
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="8.2.0" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="appsettings.shared.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</None>
|
||||
<None Update="appsettings.shared.Development.json">
|
||||
<None Update="appsettings.shared.development.json">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
<DependentUpon>appsettings.shared.json</DependentUpon>
|
||||
</None>
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
{
|
||||
"MediaSettings": {
|
||||
"RootDirectory": "wwwroot/media"
|
||||
},
|
||||
"CommonSettings": {
|
||||
"Theme": "LuminaDark"
|
||||
},
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=localhost;Database=Lumina;User Id=sa;Password=Password123;"
|
||||
"DefaultConnection": "Server=<host>;Database=<database>;User Id=<user>;Password=<password>;"
|
||||
},
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
@@ -18,4 +21,4 @@
|
||||
"WithThreadId"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user