
Return Convert.ToBase64String(tokenBuffer) Using (RNGCryptoServiceProvider cryptRNG = new RNGCryptoServiceProvider()) (This is a copy of my answer to How can I generate random 8 character, alphanumeric strings in C#?) Ulong value = BitConverter.ToUInt64(bytes, i * 8) New RNGCryptoServiceProvider().GetBytes(bytes) Throw new ArgumentException("characterSet must not be empty", "characterSet") Var characterArray = characterSet.Distinct().ToArray()

Throw new ArgumentNullException("characterSet") Throw new ArgumentException("length is too big", "length") If (length int.MaxValue / 8) // 250 million chars ought to be enough for anybody Public static string GetRandomString(int length, IEnumerable characterSet) Return GetRandomString(length, alphanumericCharacters) Public static string GetRandomAlphanumericString(int length)

The second and third property are achieved by using RNGCryptoServiceProvider instead of System.Random. For small alphabets (such as the 62 characters from the question) this leads to negligible bias. The first property is achieved by taking a 64 bit value modulo the alphabet size. It's secure, since I expect people to use this for passwords or other security tokens.Generating an 8 character string (~47 bits of entropy) is meaningless if your PRNG only generates 2 billion (31 bits of entropy) different values. It outputs more than a few billion strings for each argument set.The distribution of strings is almost uniform (don't care about minor deviations, as long as they're small).
