Created
May 23, 2022 17:30
-
-
Save rjygraham/eac2c5c66404e5dda5a6f18acce8eb69 to your computer and use it in GitHub Desktop.
.NET 6 cryptographic random string generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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