Skip to content

Instantly share code, notes, and snippets.

@rjygraham
Created May 23, 2022 17:30
Show Gist options
  • Save rjygraham/eac2c5c66404e5dda5a6f18acce8eb69 to your computer and use it in GitHub Desktop.
Save rjygraham/eac2c5c66404e5dda5a6f18acce8eb69 to your computer and use it in GitHub Desktop.
.NET 6 cryptographic random string generator
public static class RandomStringGenerator
{
public static string Next(int length)
{
var chars = new byte[length];
for (var i = 0; i < length;)
{
// 0-9: 48-57
// A-Z: 65-90
var next = RandomNumberGenerator.GetInt32(48, 91);
// Ensure generated value doesn't fall between 58-64
if (next < 58 || next > 64)
{
chars[i] = Convert.ToByte(next);
i++;
}
}
return Encoding.UTF8.GetString(chars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment