sec: save readonly byte array instead string

This commit is contained in:
Polianin Nikita 2024-12-26 08:44:05 +03:00
parent cfe08dcf9b
commit 97187a8e45
2 changed files with 29 additions and 4 deletions

View File

@ -6,11 +6,29 @@ using Mirea.Api.Security.Common.Interfaces;
using Mirea.Api.Security.Services;
using System;
using System.Collections.Generic;
using System.Text;
namespace Mirea.Api.Security;
public static class DependencyInjection
{
private static ReadOnlyMemory<byte> NormalizeKey(string key, int requiredLength)
{
var keyBytes = Encoding.UTF8.GetBytes(key);
if (keyBytes.Length < requiredLength)
{
var normalizedKey = new byte[requiredLength];
Array.Copy(keyBytes, normalizedKey, keyBytes.Length);
return new ReadOnlyMemory<byte>(normalizedKey);
}
if (keyBytes.Length > requiredLength)
Array.Resize(ref keyBytes, requiredLength);
return new ReadOnlyMemory<byte>(keyBytes);
}
public static IServiceCollection AddSecurityServices(this IServiceCollection services, IConfiguration configuration)
{
var saltSize = int.Parse(configuration["SECURITY_SALT_SIZE"]!);
@ -61,8 +79,13 @@ public static class DependencyInjection
providers.Add(provider, (clientId, secret));
}
services.AddSingleton(provider => new OAuthService(provider.GetRequiredService<ILogger<OAuthService>>(), providers,
configuration["SECURITY_ENCRYPTION_TOKEN"]!));
services.AddSingleton(provider => new OAuthService(
provider.GetRequiredService<ILogger<OAuthService>>(),
providers,
provider.GetRequiredService<ICacheService>())
{
SecretKey = NormalizeKey(configuration["SECURITY_ENCRYPTION_TOKEN"]!, 32)
});
return services;
}

View File

@ -20,6 +20,8 @@ namespace Mirea.Api.Security.Services;
public class OAuthService(ILogger<OAuthService> logger, Dictionary<OAuthProvider, (string ClientId, string Secret)> providers, string secretKey)
{
public required ReadOnlyMemory<byte> SecretKey { private get; init; }
private static readonly Dictionary<OAuthProvider, OAuthProviderUrisData> ProviderData = new()
{
[OAuthProvider.Google] = new OAuthProviderUrisData
@ -101,9 +103,9 @@ public class OAuthService(ILogger<OAuthService> logger, Dictionary<OAuthProvider
return userInfo?.MapToInternalUser();
}
private static string GetHmacString(RequestContextInfo contextInfo, string secretKey)
private string GetHmacString(RequestContextInfo contextInfo)
{
var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secretKey));
var hmac = new HMACSHA256(SecretKey.ToArray());
return Convert.ToBase64String(hmac.ComputeHash(
Encoding.UTF8.GetBytes($"{contextInfo.Fingerprint}_{contextInfo.Ip}_{contextInfo.UserAgent}")));
}