Unable to Decrypt a text containg + symbol using AES 256bit Decryption:javax.crypto.BadPaddingException: Given final block not properly padded

巧了我就是萌 提交于 2019-12-13 08:10:01

问题


Hi I am not able to decrypt a text containing '+' symbol inside the JSP page, I get the following error javax.crypto.BadPaddingException: Given final block not properly padded.

However the code works fine if I run from Eclipse or if I convert the code into Executable Jar.

JARS used : local_policy.jar US_export_policy.jar

Below is my Java code

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:


I can't speak to the Java code but Base64 strings are frequently not valid across a QueryString. You will need to URL Encode your Base64 encoded data if passing the data on the QueryString. Also the plus sign + has a semantic meaning within the QueryString. Yet another reason to URL Encode your data (and possible cause of your issue.)

String data = URLEncoder.encode(myBase64);



来源:https://stackoverflow.com/questions/23886913/unable-to-decrypt-a-text-containg-symbol-using-aes-256bit-decryptionjavax-cry

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