Last active
January 20, 2021 05:26
-
-
Save gsscoder/5468233e3d115544392d9243cabe91c5 to your computer and use it in GitHub Desktop.
C# cryptographic random string generator
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
// 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