Created
December 4, 2012 04:14
-
-
Save codingoutloud/4200537 to your computer and use it in GitHub Desktop.
Generate a random string that is URL safe.
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
using System; | |
using System.Security.Cryptography; | |
using System.Web; | |
namespace DevPartners | |
{ | |
// author: Bill Wilder, @codingoutloud | |
// original: https://gist.github.com/4200537 | |
public static class RandomTokenGenerator | |
{ | |
/// <summary> | |
/// Generate a random string that is URL safe. | |
/// </summary> | |
/// <param name="strength">Literally, number of base bytes in random sequence. The returned | |
/// string is larger than the sequence of bytes since it is encoded to be URL safe.</param> | |
/// <returns>Random URL-safe string. Can be used as part of query string.</returns> | |
public static string GenerateUrlSafeToken(int strength = 16) | |
{ | |
var random = new Random((int)DateTime.Now.Ticks); | |
var randomBytes = new byte[strength]; | |
random.NextBytes(randomBytes); // fills randomBytes with random bytes | |
var token = HttpServerUtility.UrlTokenEncode(randomBytes); // unlike straight-up Base64, safe in URLs | |
return token; | |
} | |
/// <summary> | |
/// Generate a cryptographically-random string that is URL safe. Slower than GenerateUrlSafeToken. | |
/// </summary> | |
/// <param name="strength">Literally, number of base bytes in random sequence. The returned | |
/// string is larger than the sequence of bytes since it is encoded to be URL safe.</param> | |
/// <returns>Random URL-safe string. Can be used as part of query string.</returns> | |
public static string GenerateCryptographicUrlSafeToken(int strength = 16) | |
{ | |
var random = new RNGCryptoServiceProvider(); | |
var randomBytes = new byte[strength]; | |
random.GetBytes(randomBytes); // fills randomBytes with random bytes | |
var token = HttpServerUtility.UrlTokenEncode(randomBytes); // unlike straight-up Base64, safe in URLs | |
return token; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How many random bytes should we use? I don't know, but here are some reference/comparison values: