Skip to content

Instantly share code, notes, and snippets.

@gsscoder
Last active January 20, 2021 05:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gsscoder/5468233e3d115544392d9243cabe91c5 to your computer and use it in GitHub Desktop.
Save gsscoder/5468233e3d115544392d9243cabe91c5 to your computer and use it in GitHub Desktop.
C# cryptographic random string generator
// Requires: https://github.com/gsscoder/csharpx
using System;
using System.Linq;
using CSharpx;
static class RandomString
{
const string _alphanumeric = "abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string _chars = "abcdefghijklmnopqrstuvwxyz0123456789!\"#$%&'()*@[\\]^_`{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZ";
const string _charsNoQuotes = "abcdefghijklmnopqrstuvwxyz0123456789!#$%&()*@[\\]^_{|}~ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static Random _random = new CryptoRandom();
public static string Generate(int length, bool alphanumeric = true, bool noQuotes = false)
{
if (noQuotes && alphanumeric) throw new ArgumentException(
nameof(noQuotes), "noQuotes cannot be true when alphanumeric is true.");
var chars = alphanumeric ? _alphanumeric : (noQuotes ? _charsNoQuotes : _chars);
return new string((from c in Enumerable.Repeat(chars, length)
select c[_random.Next(c.Length)]).ToArray());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment