IllegalBlockSizeException: Input length must be multiple of 8 when decrypting with padded cipher

Phanimadhavi Vasantala picture Phanimadhavi Vasantala · Jun 20, 2013 · Viewed 37.3k times · Source

I have the below method:

public String decrypt(String strToBeDecrypted) {
    try {
        strToBeDecrypted = URLDecoder.decode(strToBeDecrypted, "UTF-8");
        DESKeySpec desKeySpec = new DESKeySpec(key);
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey skey = keyFactory.generateSecret(desKeySpec);

        IvParameterSpec ivSpec = new IvParameterSpec(iv);

        cipher.init(Cipher.DECRYPT_MODE, skey, ivSpec);

        byte[] keyByteArray = new BASE64Decoder().decodeBuffer(strToBeDecrypted);

        byte[] original = cipher.doFinal(keyByteArray);

        return new String(original, "UTF-8");
    } catch (Exception e) {
        logger.error(ExceptionUtil.getDetailedMessage(e));
    }
    return "";
}

This is throwing

"name=javax.crypto.IllegalBlockSizeException;message=Input length must be multiple of 8 when decrypting with padded cipher;"

at the below line:

 byte[] original = cipher.doFinal(keyByteArray);

Can someone please tell me whats the problem here?

Answer

Rushyo picture Rushyo · Oct 4, 2013

The input length it's referring to is the length of your ciphertext (strToBeDecrypted), which it expects to be a multiple of the block size. It is implied that by default the library is expecting your input to be padded.

That means either you either need to set the padding to 'none' when decrypting (as that was the 'padding' used when encrypting) or you've corrupted the ciphertext somehow.

Try changing "DES" to "DES/ECB/NoPadding". I don't know what the default cipher mode is for your implementation, but it's typically "ECB" or "CBC". If neither of those two work then you're corrupting your ciphertext somewhere along the line.