Android DES Decrypt badpaddingexception: pad block corrupted

蓝咒 提交于 2019-12-03 21:31:02
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);

cipher.init(Cipher.DECRYPT_MODE, key);
cipher.update(cipherBytes);

// byte[] plaintext = cipher.doFinal(cipherBytes);
//                                   ^-- You shouldn't pass cipherBytes twice.
//                                   v-- instead use the parameter-less method:
byte[] plaintext    = cipher.doFinal();

Padding exception occur when the last cipher text block does not compute to valid plain text. This would happen if last ciphertext block is corrupted or the key is incorrect. For CBC mode it would also happen if the second to last ciphertext was altered (but you are using ECB mode encryption).

In your case, the deriveKeyDES() is always generating a random key. Although we didn't get the actual calls to the security methods, I would presume you use a different key for encryption and decryption. In that case there is a very high chance that the resulting plain text does not contain valid padding bytes.

Rasmus answer certainly points to an error in your code, and it would screw up your timings and return a the plain text two times, but it would not remove the BadPaddingException.

I had the same problem in one source code, and IllegalBlockSizeException in another one. Solved this two problems by return encoding data like:

 public String encrypt(String input) {
    try {
        byte[] inputBytes = input.getBytes("UTF-8");
        byte[] enc = encryptCipher.doFinal(inputBytes);
        // and problem was in return encoding. That's how i fixed it 
        return Base64.encodeToString(enc,Base64.DEFAULT);
        .....
          }
        }

Give u a code for decrypt:

 public String decrypt(String input) {
    try {
        byte[] dec = Base64.decode(input.getBytes(), Base64.DEFAULT);
        //here had exception
        byte[] utf8 = decryptCipher.doFinal(dec);
        return new String(utf8,"UTF8");
    } catch (IOException | BadPaddingException | IllegalBlockSizeException e) {
        e.printStackTrace();
    }
    return null;
}

I should submit, that had BadPaddingException and IllegalBlockSizeException only in decrypt method byte[] utf8 = decryptCipher.doFinal(dec); (u had exeption in the same place: byte[] plaintext = cipher.doFinal(cipherBytes);), but real wrong is in encrypt method(return value)

That's why i recommend u to use that code in encrypt method:

return Base64.encodeToString(enc,Base64.DEFAULT);

P.S Tried to a give full answer on your question.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!