AES 解密:javax.crypto.IllegalBlockSizeException:解密的最后一个块不完整

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23441208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 23:00:26  来源:igfitidea点击:

AES Decryption : javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

javaexceptionencryptioncryptographyaes

提问by iAviatorJose

I am trying to decrypt an encrypted data obtained from a web service using AES128 cryptography.

我正在尝试使用 AES128 加密解密从 Web 服务获得的加密数据。

following is the code i am using to achieve the same.

以下是我用来实现相同目的的代码。

But i always end up with the following exception: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

但我总是以以下例外结束: javax.crypto.IllegalBlockSizeException: last block incomplete in decryption

public static String decrypt(String strToDecrypt)
    {

        try
        {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
            final SecretKeySpec secretKey = new SecretKeySpec(AppConstants.AESEncryptionKey.getBytes("UTF8"), "AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey,new IvParameterSpec(new byte[16])); //new IvParameterSpec(new byte[16])
            byte base64Data[] = Base64.encode(strToDecrypt.getBytes(), Base64.DEFAULT);
            @SuppressWarnings("unused")
            String s = base64Data.toString();
            byte decBytes[] = cipher.doFinal(base64Data);
            String decStr = new String(decBytes);
            return decStr;
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

Please Pour in your valuable inputs as i am badly stuck over here.

请倾注您的宝贵意见,因为我被困在这里。

采纳答案by Maarten Bodewes

You are encoding the base 64 encoded ciphertext instead of decoding it. Depending on your Base64you need to call a function that decodes from a Stringor CharSequenceto an array of bytes, and then decrypt that. Please test if the result is a multiple of the block size, 16 bytes for AES.

您正在对 base 64 编码的密文进行编码,而不是对其进行解码。根据Base64您的需要,您需要调用一个从字节数组StringCharSequence字节数组解码的函数,然后对其进行解密。请测试结果是否是块大小的倍数,AES 为 16 字节。

回答by UVM

You have to call Base64.decodeBase64(s). Then call Cipher.doFinal()

您必须调用 Base64.decodeBase64(s)。然后调用 Cipher.doFinal()

Cipher.doFinal(Base64.decodeBase64(s));

Cipher.doFinal(Base64.decodeBase64(s));

回答by Yogesh Rathi

Important note

重要的提示

In my case this issue came because of encryption not done properly, when i try to encrypt data that time my code through error that's why in middle encryption is terminated, so once you check your encryption is working properly.

在我的情况下,这个问题是因为加密没有正确完成,当我尝试加密数据时,我的代码通过错误,这就是为什么中间加密被终止, 所以一旦你检查你的加密是否正常工作。