Search code examples
c#random

How can I generate cryptographically strong random strings with a given length


I need to generate cryptographically strong random alphanumeric strings with a specified length, only using the following characters.

  • A-Z
  • a-z
  • 0-9

Is there a way to accomplish this in C#?


Solution

  • You can use class RandomNumberGenerator to generate cryptographically-secure random numbers to do this, for example:

    string allowed = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    int strlen = 10; // Or whatever
    char[] randomChars = new char[strlen];
    
    for (int i = 0; i < strlen; i++)
    {
        randomChars[i] = allowed[RandomNumberGenerator.GetInt32(0, allowed.Length)];
    }
    
    string result = new string(randomChars);
    
    Console.WriteLine(result);