Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use .toString(32) and not .toString(36)?

Curious:

A lot of people will use the [Number].toString(32) method to do things like generate session IDs, e.g. something like:

public class SessionID{

    private static SecureRandom ran = new SecureRandom();

    public static String next() {
        return new BigInteger(130, ran).toString(32);
    }

}

I've also seen it used for translating bytes of hashed passwords to a string format. But why not use .toString(36)? Base 32 does not include z,y,x, or w, so what's the reasoning behind using it? (Guessing something to do with 32 = 2^5, but I'd appreciate a better answer.)

like image 381
Joseph Nields Avatar asked Feb 11 '23 15:02

Joseph Nields


1 Answers

As you mentioned, 32 = 2^5, so each character will represent exactly 5 bits. Since 128 bits is preferred for strong security, 26 base-32 digits (32^26) exactly equals 2^130, so each character will represent exactly 5 bits, and 130 bits can be evenly divided into characters and you can squeeze a couple of extra bits in without any additional characters. If you use base 36 instead, you need 6 bits per character. You can fit 129 bits into 25 characters, but there is some wasted space.

like image 99
Tito Avatar answered Feb 19 '23 13:02

Tito