1

I am using google authenticator for TOTP generation and it uses a base32 encoded string to do so.

The secret that I have is Hex encoded and I need to convert it to Base32 before I can use it.

The following site does it perfectly, but I need it in JAVA. : http://tomeko.net/online_tools/hex_to_base32.php?lang=en

I am very new to encoding and decoding. Any thoughts on how to go about it?

7
  • I first need to decode the hex and then convert it to base 32? Commented Jun 20, 2017 at 13:57
  • I need to convert Hex to Base32, not just encode a string to Base32. Thanks Commented Jun 20, 2017 at 14:04
  • Easiest approach. Otherwise you should implement the algorithm on your own Commented Jun 20, 2017 at 14:04
  • 1
    I used the method mentioned here: stackoverflow.com/questions/13990941/…, But I am unable to get the same output as the one on the website that I mentioned Commented Jun 20, 2017 at 14:06
  • 1
    I also tried to use the base32 encoder on a hex and still, doesn't give me the required output. Commented Jun 20, 2017 at 14:09

1 Answer 1

2

Okay, It was fairly simple. All I had to do was decode the Hex to a byte[] array and then encode it to Base32 using Apache Commons Codec Java library This is the code

String hexToConvert = "446a1837e14bfec34a9q0141a55ec020f73e15f4";
byte[] hexData = hexStringToByteArray(hexToConvert);       
Base32 base32 = new Base32();
String encodeBase32 = base32.encodeAsString(hexData);
System.out.println("Base 32 String: " + encodeBase32);

Helper Function: this is from Convert a string representation of a hex dump to a byte array using Java?

public static byte[] hexStringToByteArray(String s) {
    int len = s.length();
    byte[] data = new byte[len / 2];
    for (int i = 0; i < len; i += 2) {
        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                             + Character.digit(s.charAt(i+1), 16));
    }
    return data;
}
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.