From d05ba5349fd44eeef83335584d28bd9c2a4a08df Mon Sep 17 00:00:00 2001 From: Polianin Nikita Date: Wed, 29 May 2024 04:48:37 +0300 Subject: [PATCH] refactor: isolate key generation --- Security/Services/GeneratorKey.cs | 28 ++++++++++++++++++++++++ Security/Services/PasswordHashService.cs | 23 +------------------ 2 files changed, 29 insertions(+), 22 deletions(-) create mode 100644 Security/Services/GeneratorKey.cs diff --git a/Security/Services/GeneratorKey.cs b/Security/Services/GeneratorKey.cs new file mode 100644 index 0000000..79a0430 --- /dev/null +++ b/Security/Services/GeneratorKey.cs @@ -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 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 utf8Bytes = new byte[Base64.GetMaxEncodedToUtf8Length(randomBytes.Length)]; + + Base64.EncodeToUtf8(randomBytes, utf8Bytes, out _, out _); + return Encoding.UTF8.GetString(utf8Bytes); + } +} \ No newline at end of file diff --git a/Security/Services/PasswordHashService.cs b/Security/Services/PasswordHashService.cs index b9cc41c..8673222 100644 --- a/Security/Services/PasswordHashService.cs +++ b/Security/Services/PasswordHashService.cs @@ -1,6 +1,5 @@ using Konscious.Security.Cryptography; using System; -using System.Buffers.Text; using System.Text; namespace Mirea.Api.Security.Services; @@ -41,29 +40,9 @@ public class PasswordHashService return result == 0; } - public static ReadOnlySpan 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 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) { - var salt = GenerateRandomKeyBytes(SaltSize); + var salt = GeneratorKey.GenerateBytes(SaltSize); var hash = HashPassword(password, salt); return (Convert.ToBase64String(salt), Convert.ToBase64String(hash));