Created
June 1, 2017 22:09
-
-
Save Martyr2/76e434512b6b4f044d28e10686749e97 to your computer and use it in GitHub Desktop.
Generates a random string of a specified length. Defaults to 25 characters.
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
/// <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