无法使用AES 256位解密包含+符号的文本解密:javax.crypto.BadPaddingException:给定最终块未正确填充

时间:2014-05-27 10:21:52

标签: java jsp encryption aes

您好我无法解密JSP页面中包含“+”符号的文本,我收到以下错误javax.crypto.BadPaddingException:给定最终块没有正确填充。

但是,如果我从Eclipse运行或者将代码转换为Executable Jar,则代码可以正常工作。

JARS使用:            local_policy.jar            的US_export_policy.jar

以下是我的Java代码

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Decrypt256bit {

private static Key key;

private static Cipher cipher;

static {
    key = new SecretKeySpec("P@ssw0Rd!@#**&&&P@ssw0Rd!@#**&&&".getBytes(), "AES");
    try {
        cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING","SunJCE");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static String encryptData(String plainText) {
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encrypted = cipher.doFinal(plainText.getBytes());
        return new BASE64Encoder().encode(encrypted);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

public static String decryptData(String encryptedValue) {
    try {
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
        int maxKeyLen = Cipher.getMaxAllowedKeyLength("AES");
        System.out.println("Length==="+maxKeyLen);
        return new String(cipher.doFinal(decordedValue));
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}

1 个答案:

答案 0 :(得分:1)

我不能说Java代码,但Base64字符串在QueryString中经常无效。如果在QueryString上传递数据,您将需要对您的Base64编码数据进行URL编码。此外,加号+在QueryString中具有语义含义。网址编码数据的另一个原因(以及问题的可能原因。)

  

String data = URLEncoder.encode(myBase64);