Skip to content

Instantly share code, notes, and snippets.

@codingoutloud
Created December 4, 2012 04:14
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codingoutloud/4200537 to your computer and use it in GitHub Desktop.
Save codingoutloud/4200537 to your computer and use it in GitHub Desktop.
Generate a random string that is URL safe.
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;
}
}
}
@codingoutloud
Copy link
Author

How many random bytes should we use? I don't know, but here are some reference/comparison values:

  • GUID - example: 1e57507f-1864-4523-9a32-89fd9a9852ac - 36 unicode chars, 72 bytes
  • hash = 20 bytes
  • signature = 128 bytes
  • GUID w/o hyphens = 32 chars for session token

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment