jeudi 26 juillet 2018

Efficiently convert random bytes to string without much loss of entropy

I need a cryptographically random string to serve as the session identifier in my Web app. Here is my current implementation with libsodium:

char session_id[81];
sprintf(session_id, "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32
        "%"
        PRIx32,
        randombytes_random(), randombytes_random(), randombytes_random(), randombytes_random(),
        randombytes_random(), randombytes_random(), randombytes_random(), randombytes_random());

Which is the most obvious way. This problem is that most of the key space is unused: there are 36 alphanumeric characters even if we ignore case sensitivity, but only 16 of which (0-9, A-E, and maybe X from the 0X prefix) would appear in the resulting string. I'd like to know if there is a way to improve the current approach by making use of more of the key space.

The convert should be as efficient as possible, but on the other hand I hope most of the randomness is preserved. Please note that I don't expect ALL entropy to be preserved if that operation would be too expansive. Instead, I'm seeking a balance between the length of the resulting string, performance, and the amount of entropy.

I'm already using libsodium for other functionalities in my project, and I'd like to stick to it. Please avoid suggesting another library unless you have a really good reason. Thanks in advance.




Aucun commentaire:

Enregistrer un commentaire