Created
January 13, 2022 11:25
-
-
Save yanandrey/e67ff511c2ac5131edf59aa80403ccb8 to your computer and use it in GitHub Desktop.
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 RandomStringHelper | |
{ | |
public static string RandomString(int length) | |
{ | |
const string valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; | |
var res = new StringBuilder(); | |
using (var rng = new RNGCryptoServiceProvider()) | |
{ | |
byte[] uintBuffer = new byte[sizeof(uint)]; | |
while (length-- > 0) | |
{ | |
rng.GetBytes(uintBuffer); | |
var num = BitConverter.ToUInt32(uintBuffer, 0); | |
res.Append(valid[(int)(num % (uint)valid.Length)]); | |
} | |
} | |
return res.ToString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment