diff --git a/Endpoint/Program.cs b/Endpoint/Program.cs index bebb589..06fc830 100644 --- a/Endpoint/Program.cs +++ b/Endpoint/Program.cs @@ -79,7 +79,7 @@ public class Program if (string.IsNullOrEmpty(secretForward!.SecretForwardToken)) { - secretForward.SecretForwardToken = GeneratorKey.GenerateBase64(18); + secretForward.SecretForwardToken = GeneratorKey.GenerateAlphaNumeric(16); secretForward.SaveSetting(); } diff --git a/Security/Services/GeneratorKey.cs b/Security/Services/GeneratorKey.cs index 79a0430..b71bfab 100644 --- a/Security/Services/GeneratorKey.cs +++ b/Security/Services/GeneratorKey.cs @@ -1,11 +1,30 @@ using System; using System.Buffers.Text; +using System.Linq; using System.Text; namespace Mirea.Api.Security.Services; public static class GeneratorKey { + public static string GenerateAlphaNumeric(int size, string? excludes = null, string? includes = null) + { + var random = new Random(); + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + + string charsForGenerate = excludes? + .Aggregate(chars, (current, ex) => current.Replace(ex.ToString(), string.Empty)) ?? chars; + + if (!string.IsNullOrEmpty(includes)) + charsForGenerate = includes + .Aggregate(charsForGenerate, (current, include) => + current.Contains(include) ? current : current + include); + + return new string(Enumerable.Repeat(charsForGenerate, size) + .Select(s => s[random.Next(s.Length)]) + .ToArray()); + } + public static ReadOnlySpan GenerateBytes(int size) { var key = new byte[size];