From 809b513e7a3f5a4f7faf64b02d9ed83e81c540b8 Mon Sep 17 00:00:00 2001 From: whoswhip Date: Sat, 14 Feb 2026 18:30:58 -0500 Subject: [PATCH] feat(backend:utilities): implement GenerateSecureRandomString function that uses RandomNumberGenerator --- SharpbinV3.Server/Utilities.cs | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/SharpbinV3.Server/Utilities.cs b/SharpbinV3.Server/Utilities.cs index 3647c13..b1e1d62 100644 --- a/SharpbinV3.Server/Utilities.cs +++ b/SharpbinV3.Server/Utilities.cs @@ -11,6 +11,32 @@ namespace SharpbinV3.Server return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); } + public static string GenerateSecureRandomString(int length) + { + const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; + Span buffer = stackalloc byte[128]; + + var result = new char[length]; + int pos = 0; + + while (pos < length) + { + RandomNumberGenerator.Fill(buffer); + + foreach (byte b in buffer) + { + if (b >= 248) + continue; // 248 is the largest multiple of 62 < 256 + + result[pos++] = chars[b % chars.Length]; + if (pos == length) + break; + } + } + + return new string(result); + } + public static string ComputeSha256(string input) { var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);