Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
273 views
in Technique[技术] by (71.8m points)

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

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...