Skip to content

Instantly share code, notes, and snippets.

@yanandrey
Created January 13, 2022 11:25
Show Gist options
  • Save yanandrey/e67ff511c2ac5131edf59aa80403ccb8 to your computer and use it in GitHub Desktop.
Save yanandrey/e67ff511c2ac5131edf59aa80403ccb8 to your computer and use it in GitHub Desktop.
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