AES / CBC / PKCS5Padding Java加密错误 - javax.crypto.BadPaddingException:给定最终块未正确填充

时间:2012-02-21 16:31:17

标签: java encryption aes padding

我尝试使用AES / CBC / PKCS5Padding对字符串进行加密解密 我得到了这个异常:javax.crypto.BadPaddingException:给定最终块未正确填充

我试图加密的字符串:ftp.clarapoint.com

这是我的加密代码:

cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");        
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] data = cipher.doFinal(stringDec.getBytes());
byte[] iv = cipher.getIV();

我将解密方法转移如下: aesKey,data and iv

解密代码:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
AlgorithmParameters.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
byte[] decrypted = cipher.doFinal(data);

谢谢!

1 个答案:

答案 0 :(得分:4)

您没有正确传输密钥或密码文本,因为此代码确实运行:

private static void testCode() {
    try {
        String stringDec = "Hi there";
        SecretKey aesKey = new SecretKeySpec(new byte[16], "AES");

        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);

        // no encoding given, don't use getBytes() without a Charset.forName("UTF-8")
        byte[] data = cipher.doFinal(stringDec.getBytes());
        byte[] iv = cipher.getIV();

        // doesn't do anything
        AlgorithmParameters.getInstance("AES");

        cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(iv));
        byte[] decrypted = cipher.doFinal(data);
        System.out.println(new String(decrypted));
    } catch (GeneralSecurityException e) {
        throw new IllegalStateException(e);
    }
}