Skip to content

Instantly share code, notes, and snippets.

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 codingoutloud/4121999 to your computer and use it in GitHub Desktop.
Save codingoutloud/4121999 to your computer and use it in GitHub Desktop.
Generate a random(ish) token that is safe to be used in a URL. Allow caller to specify strength though number of generated random chars.
// Bill Wilder | @codingoutloud | http://www.cloudarchitecturepatterns.com | Nov 2012
// Original: https://gist.github.com/4121999
// Similar GenerateUrlSafeRandomToken.cs, except upgraded to use crypto-strength RNG
// Add reference to System.Web.dll
public static string GenerateUrlSafeCryptographicallyStrongRandomToken(int strength = 16)
{
using (var rng = new RNGCryptoServiceProvider())
{
var randomBytes = new byte[strength];
rng.GetBytes(randomBytes);
var token = HttpServerUtility.UrlTokenEncode(randomBytes); // unlike Base64, this is safe for use in URLs
return token;
}
}
// Bill Wilder | @codingoutloud | http://www.cloudarchitecturepatterns.com | Nov 2012
// Original: https://gist.github.com/4121999
public static string GenerateUrlSafeRandomToken(int strength = 16)
{
var random = new Random((int) DateTime.Now.Ticks);
var randomBytes = random.NextBytes(new byte[strength]);
var token = HttpServerUtility.UrlTokenEncode(randomBytes); // unlike Base64, this is safe for use in URLs
return token;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment