mardi 1 mars 2016

How to use urandom to generate all possible base64 characters?

In a base64 digits you could save up to 6 bits (2**6 == 64).

Which means that you could fit 3 bytes in 4 base64 digits.

64**4 == 2**24

That's why:

0x000000 == 'AAAA'
0xFFFFFF == '////'

This means that a random string of 3 bytes is equivalent to a base64 string of 4 characters.

However if I am converting a number of bytes which is not a multiple of 3 in a base64 string, I will not be able to generate all the combination of the base64 string.

Let's take an example:

  • If I want a random 7 characters base64 string, I would need to generate 42 random bits (64**7 == 2**42).

If I am using urandom to get 5 random bytes I will get only 40 bits (5*8) and if ask for 6 I will get 48 bits (6*8).

Can I ask for 6 bytes and use a mask to short it down to 5 or will it break my random repartition?

One solution:

hex(0x123456789012 & 0xFFFFFFFFFF)
'0x3456789012'

Another one:

hex(0x123456789012 >> 8)
'0x1234567890'

What do you think?




Aucun commentaire:

Enregistrer un commentaire