mardi 11 octobre 2022

Generating a random string using RandomNumberGenerator - Is it random enough?

I'm generating random strings that ideally should be unique (I'm checking uniqueness as they are inserted into the DB), the strings are 12 characters long.
Here is my code

var alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var uniqueCode = new char[12];
for (var i = 0; i < codeLength; i++)
{
   uniqueCode[i] = alphabet[RandomNumberGenerator.GetInt32(alphabet.Length)];
}

If I'm using RandomNumberGenerator which is cryptographic do i need to worry about adding any other uniqueness? Masking, etc
Looking at the C# port of nanoId i can see there is some masking but is this really needed if RandomNumberGenerator is truly random ?

NanoId Masking Example

        internal static int Clz32(int x)
        {
            const int numIntBits = sizeof(int) * 8; //compile time constant
            //do the smearing
            x |= x >> 1;
            x |= x >> 2;
            x |= x >> 4;
            x |= x >> 8;
            x |= x >> 16;
            //count the ones
            x -= x >> 1 & 0x55555555;
            x = (x >> 2 & 0x33333333) + (x & 0x33333333);
            x = (x >> 4) + x & 0x0f0f0f0f;
            x += x >> 8;
            x += x >> 16;
            return numIntBits - (x & 0x0000003f); //subtract # of 1s from 32
        }

https://github.com/codeyu/nanoid-net/blob/master/src/Nanoid/Nanoid.cs




Aucun commentaire:

Enregistrer un commentaire