3

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 ?

Community
  • 1
  • 1
Nitin Verma
  • 485
  • 4
  • 19
  • 1
    The word "base" is being used in 2 different contexts here: (1) the encoding scheme known as "base 32" for converting binary data to text; and (2) Taking a number and converting it to the equivalent number in a different "base" (more precisely, a different _radix_). In `Long.toString(key,32)`, the `32` is a radix. The English language can be a slippery eel. – andrewJames Aug 15 '20 at 19:12

1 Answers1

1

"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===.

Joni
  • 108,737
  • 14
  • 143
  • 193