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?

user2013919
  • 43
  • 1
  • 5
  • I first need to decode the hex and then convert it to base 32? – user2013919 Jun 20 '17 at 13:57
  • I need to convert Hex to Base32, not just encode a string to Base32. Thanks – user2013919 Jun 20 '17 at 14:04
  • Easiest approach. Otherwise you should implement the algorithm on your own – xenteros Jun 20 '17 at 14:04
  • Basically implement 32 division on hex number and you'll get the solution – xenteros Jun 20 '17 at 14:05
  • 1
    I used the method mentioned here: https://stackoverflow.com/questions/13990941/how-to-convert-hex-string-to-java-string, But I am unable to get the same output as the one on the website that I mentioned – user2013919 Jun 20 '17 at 14:06
  • 1
    I also tried to use the base32 encoder on a hex and still, doesn't give me the required output. – user2013919 Jun 20 '17 at 14:09
  • This is not a duplicate. It doesn't matter that the second of the two steps to go from Hex to Base32 is to encode a string in Base32 (which is all that question talks about). This question is about converting to Base32 _a string which is currently encoded in Hex_, and the first step for that is decoding from Hex. It's not enough to know how to encode something in Base32. If you just do that without the first step you get wrong results. – SantiBailors Jan 04 '18 at 09:48

1 Answers1

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;
}
user2013919
  • 43
  • 1
  • 5