feat(backend:utilities): implement GenerateSecureRandomString function that uses RandomNumberGenerator

This commit is contained in:
2026-02-14 18:30:58 -05:00
parent 3374eadb56
commit 809b513e7a
+26
View File
@@ -11,6 +11,32 @@ namespace SharpbinV3.Server
return new string([.. Enumerable.Repeat(chars, length).Select(s => s[random.Next(s.Length)])]); 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<byte> 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) public static string ComputeSha256(string input)
{ {
var inputBytes = System.Text.Encoding.UTF8.GetBytes(input); var inputBytes = System.Text.Encoding.UTF8.GetBytes(input);