问题
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