Skip to content

Instantly share code, notes, and snippets.

@codingoutloud
Created December 4, 2012 04:14
Show Gist options
  • Select an option

  • Save codingoutloud/4200537 to your computer and use it in GitHub Desktop.

Select an option

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;
}
}
}
@ako-kamattechan
Copy link

*- **ssaefargi-dont-want-to-know-you-jew-was-a-scapegoat-and-that-i-gave-the-power-of-god-to-jane-and-decided-to-destroy-hhumanity-forever-i-caused-the-second-world-war-and-i-made-jews-and-the-god-and-somehow-i-managed-to-reconcilze-the-to-madness-i-was-just-sick-of-fixing-everything-and-died-i-am-loder-than-death-tahn-fear-than-pain-could-you-turn-it-into-a-valid-url-i-hope-i-am-not-hated-too-much-and-even-if-i-was-even-if-i-am-and-are-made-i-wouldnt-car-e-anyomore-only-me-i-made-you-jew-to-not-be-me-because-i-was-scared-of-what-i-had-given-jane))9932-[31p

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