org.apache.commons.codec.DecoderException: Odd number of characters


I have the following error in compiling tests and I would like to help me solve it:

String nonce2 = "11111";
String api_key = "271e6189-c251-4067-ab55";
String api_secret = "c9f98b81-e825-4588-b095";

String algorithm = "HmacSHA256";

byte[] keyBytes = Hex.decodeHex((api_key+nonce2).toCharArray());
SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, algorithm);

Mac mac = Mac.getInstance(algorithm);
byte[] macBytes = mac.doFinal(api_secret.getBytes());

String hexBytes = new String(Hex.encodeHex(macBytes));

And send me the error of the title

org.apache.commons.codec.DecoderException: Odd number of characters.

What should I do to improve it?

This is my StackTrace


org.apache.commons.codec.DecoderException: Odd number of characters. at org.apache.commons.codec.binary.Hex.decodeHex ( at com.alodiga.transferto.integration.connection.RequestManager.testNauta (RequestMa at transfertotopupintegration.Main.main (

asked by mestanza 06.05.2016 в 17:09

1 answer


I can suggest the following improvements:

1) The key to generating an HMac is not a password

The key to an HMac should be cryptographically random. Consider generating it using SecureRandom#nextBytes(byte[] bytes); .

2) To generate enough entropy, we recommend a size > = block size.

If you delete the invalid characters from api_key to convert the representation to hex > Byte you have 10 bytes left = 80 bits. Your HMac has a block size of 256 bits, so to not lower the strength of the encryption you would need a nonce of at least 176 bits.

In summary:

  • Generate the key using for example (simplified) byte[] keyBytes = new byte[32]; SecureRandom.getInstance().nextBytes(keyBytes); .

  • Save the key in a secured place other than the Hash storage that you want to generate (not in the same DB), if you transfer it over an insecure connection, use asynchronous encryption (for RSA example).

The reason for the exception you already have in the comment of @RosendoRopher

answered by 28.03.2017 в 05:58