Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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];
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