mardi 14 mai 2019

Why isn't this Base36 random string using RandomNumberGenerator randomly distributing the characters

I am trying to generate a random Base36 string using C#. I am using RandomNumberGenerator rather than Random as the code needs to be threadsafe. I have the following code setup:

private readonly RandomNumberGenerator _random = RandomNumberGenerator.Create(); 

private string GenerateBase36Token(int length)
{
    string token = string.Empty;

    for (int i = 0; i < length; i++)
    {
        byte[] bytes = new byte[100];
        _random.GetBytes(bytes);
        token += ToBase36String(bytes)[0];
    }

    return token;
}

private string ToBase36String(byte[] toConvert)
{
    const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    BigInteger dividend = new BigInteger(toConvert);
    StringBuilder builder = new StringBuilder();

    while (dividend != 0)
    {
        BigInteger remainder;
        dividend = BigInteger.DivRem(dividend, alphabet.Length, out remainder);
        builder.Insert(0, alphabet[Math.Abs((int)remainder)]);
    }

    return builder.ToString();
}

This appears to work however looking at the results it is apparent that the strings are not evenly distributing the potential characters. There are a lot of repeating letters and numbers very rarely appear.

Is the problem just taking the first characters of the random string or is there an issue with how the string is being built?




Aucun commentaire:

Enregistrer un commentaire