Skip to content

Instantly share code, notes, and snippets.

@Martyr2
Created June 1, 2017 22:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Martyr2/76e434512b6b4f044d28e10686749e97 to your computer and use it in GitHub Desktop.
Save Martyr2/76e434512b6b4f044d28e10686749e97 to your computer and use it in GitHub Desktop.
Generates a random string of a specified length. Defaults to 25 characters.
/// <summary>
/// Gets a random crypto string
/// </summary>
/// <param name="length">The length of the string to generate</param>
/// <remarks>Typically the length is 25</remarks>
/// <returns>Returns a random string of characters of length size.</returns>
public static string GetRandomString(int length = 25)
{
// Set the character space
string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider()) {
byte[] randomBytes = new byte[length];
char[] randomChars = new char[length];
rng.GetBytes(randomBytes);
for (int i = 0; i < length; i++) {
randomChars[i] = allowedChars[(int)randomBytes[i] % allowedChars.Length];
}
return new string(randomChars);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment