-1

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#?

  • What do you mean by cryptographically strong – Peter Smith Apr 10 '23 at 15:28
  • @PeterSmith Most of the examples I read used Random class and some people had recommended using Cryptographic classes unless we use these strings as unique identifiers. – Yashoja Lakmith Apr 10 '23 at 15:32
  • 1
    If you can live with just 0-9 and A-F (or a-f), you can just call `RandomNumberGenerator.GetBytes` and take the result and convert it to a hex string using one of the many methods described here: https://stackoverflow.com/questions/311165/how-do-you-convert-a-byte-array-to-a-hexadecimal-string-and-vice-versa. – Flydog57 Apr 10 '23 at 16:42

2 Answers2

2

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

string allowed = "ABCDEFGHIJKLMONOPQRSTUVWXYZabcdefghijklmonopqrstuvwxyz0123456789";
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);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
-3

Try following :

            int randomArrayLength = 256;
            char[] characters = {
                'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm',
                'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
                'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};

            int numberOfChar = characters.Length;

            Random rand = new Random();
            string results = string.Join("", Enumerable.Range(0, randomArrayLength).Select(x => characters[rand.Next(numberOfChar)]));
jdweng
  • 33,250
  • 2
  • 15
  • 20
  • 2
    `Random` is [not cryptographically strong](https://learn.microsoft.com/en-us/dotnet/api/system.random?view=net-7.0#remarks), as OP asked for. – Magnetron Apr 10 '23 at 15:55
  • @Magnetron : I assume the string is just a seed into a crypto generator. – jdweng Apr 10 '23 at 15:57