user2064718
user2064718

Reputation: 21

How to simply generate a random base64 string compatible with all base64 encodings

In C, I was asked to write a function to generate a random Base64 string of length 40 characters (30 bytes ?). But I don't know the Base64 flavor, so it needs to be compatible with many version of Base64.

What can I do ? What is the best option ?

Upvotes: 2

Views: 7306

Answers (1)

John Zwinck
John Zwinck

Reputation: 249552

All the Base64 encodings agree on some things, such as the use of [0-9A-Za-z], which are 62 characters. So you won't get a full 64^40 possible combinations, but you can get 62^40 which is still quite a lot! You could just generate a random number for each digit, mod 62. Or slice it up more carefully to reduce the amount of entropy needed from the system. For example, given a 32-bit random number, take 6 bits at a time (0..63), and if those bits are 62 or 63, discard them, otherwise map them to one Base64 digit. This way you only need about 8, 32-bit integers to make a 40-character string.

If this system has security considerations, you need to consider the consequences of generating "unusual" Base64 numbers (e.g. an attacker could detect that your Base64 numbers are special in having only 62 symbols with just a small corpus--does that matter?).

Upvotes: 4

Related Questions