Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 290
Phanimadhavi Vasantala Avatar asked Oct 03 '22 18:10

Phanimadhavi Vasantala


1 Answers

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.

like image 126
Rushyo Avatar answered Oct 07 '22 19:10

Rushyo