refactor: isolate key generation

This commit is contained in:
Polianin Nikita 2024-05-29 04:48:37 +03:00
parent 5fde5bd396
commit d05ba5349f
2 changed files with 29 additions and 22 deletions

View File

@ -0,0 +1,28 @@
using System;
using System.Buffers.Text;
using System.Text;
namespace Mirea.Api.Security.Services;
public static class GeneratorKey
{
public static ReadOnlySpan<byte> GenerateBytes(int size)
{
var key = new byte[size];
using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
rng.GetNonZeroBytes(key);
return key;
}
public static string GenerateBase64(int size) =>
Convert.ToBase64String(GenerateBytes(size));
public static string GenerateString(int size)
{
var randomBytes = GenerateBytes(size);
Span<byte> utf8Bytes = new byte[Base64.GetMaxEncodedToUtf8Length(randomBytes.Length)];
Base64.EncodeToUtf8(randomBytes, utf8Bytes, out _, out _);
return Encoding.UTF8.GetString(utf8Bytes);
}
}

View File

@ -1,6 +1,5 @@
using Konscious.Security.Cryptography; using Konscious.Security.Cryptography;
using System; using System;
using System.Buffers.Text;
using System.Text; using System.Text;
namespace Mirea.Api.Security.Services; namespace Mirea.Api.Security.Services;
@ -41,29 +40,9 @@ public class PasswordHashService
return result == 0; return result == 0;
} }
public static ReadOnlySpan<byte> GenerateRandomKeyBytes(int size)
{
var key = new byte[size];
using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
rng.GetNonZeroBytes(key);
return key;
}
public static string GenerateRandomKeyStringBase64(int size) =>
Convert.ToBase64String(GenerateRandomKeyBytes(size));
public static string GenerateRandomKeyString(int size)
{
var randomBytes = GenerateRandomKeyBytes(size);
Span<byte> utf8Bytes = new byte[Base64.GetMaxEncodedToUtf8Length(randomBytes.Length)];
Base64.EncodeToUtf8(randomBytes, utf8Bytes, out _, out _);
return Encoding.UTF8.GetString(utf8Bytes);
}
public (string Salt, string Hash) HashPassword(string password) public (string Salt, string Hash) HashPassword(string password)
{ {
var salt = GenerateRandomKeyBytes(SaltSize); var salt = GeneratorKey.GenerateBytes(SaltSize);
var hash = HashPassword(password, salt); var hash = HashPassword(password, salt);
return (Convert.ToBase64String(salt), Convert.ToBase64String(hash)); return (Convert.ToBase64String(salt), Convert.ToBase64String(hash));