how to convert a number to base32 in java as per RFC-4648

1.8k Views Asked by At

Actually I'm trying to use TOTP in my app and google authenticator requires the key to be in base32 format. This is the reason I'm trying to convert a key to base32 format

Let's say I have a number = 150820200825235.

This wikipedia page says that RFC-4648 is the most common base32 alphabet used.

Here's my java code where I'm trying to convert a number to base 32:

    long key=150820200825235L;
    String base32Key = Long.toString(key,32);
    System.out.println(base32Key);

Now it is printing this as the output :

495e87tgcj

It contains 9 which is invalid according to RFC-4648.

how do I convert to base32 number as per RFC-4648 in java?

One more thing If the most widely used Base32 alphabet is really as per RFC-4648 then why doesn't java support it as default? or is something is wrong in my understanding/code ?

1

There are 1 best solutions below

0
Joni On

"Base32" as defined in RFC-4648 is a way to encode binary data ("arbitrary sequences of octets") in ASCII text using only numbers, upper case letters, and = for padding. You can find an implementation in the Apache Commons Codec library

If you start with a number like 150820200825235 and want to convert it into RFC 4648 base32, first you need to decide how to convert the number into a sequence of bytes.

Foe example, One way to convert a long value into bytes is using the DataOutputStream.writeLong method. This method uses 8 bytes. Using this method to write 150820200825235L and encoding the resulting bytes in base32 gives you AAAISK4QP3AZG===.