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

Rahul P picture Rahul P · Jan 12, 2015 · Viewed 8.6k times · Source

Sending hex string in url parameter and trying to convert it in to string at server side. Converting user input string by using following javascript encoding code

function encode(string) {
     var number = "";
        var length = string.trim().length;
        string = string.trim();
        for (var i = 0; i < length; i++){
            number += string.charCodeAt(i).toString(16);
            }
        return number;
}

Now I'm trying to parse hex string 419 for russian character Й in java code as follows

  byte[] bytes = "".getBytes();

   try {
        bytes = Hex.decodeHex(hex.toCharArray());
        sb.append(new String(bytes,"UTF-8"));
    } catch (DecoderException e) {      
      e.printStackTrace(); // Here it gives error 'Odd number of characters'
    }catch (UnsupportedEncodingException e) {           
      e.printStackTrace();
    }

but it gives following error

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

How it can be resolved. As there are many russian character have hex code 3 digit and due to this it is not able to convert it to .toCharArray()

Answer

Abhinav Atul picture Abhinav Atul · Feb 7, 2020

Use Base64 instead

val aes = KeyGenerator.getInstance("AES")
aes.init(128)
val secretKeySpec = aes.generateKey()
val base64 = Base64.encodeToString(secretKeySpec.encoded, 0)
val bytes = Base64.decode(base64, 0)
SecretKeySpec(bytes, 0, bytes.size, "AES") == secretKeySpec