Last active
May 11, 2016 22:24
-
-
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.
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
// 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; | |
} | |
} |
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
// 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