使用tomcat,我有兩個web應用程序,即app1和app2。我以加密的形式(使用下面的代碼)從app1發送url到app2。然後在app2 我解密了這個加密的url。但是在decryp
方法的第50行得到異常。獲取javax.crypto.IllegalBlockSizeException:使用填充密碼解密時,輸入長度必須是16的倍數?
"Getting javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher"
雖然爲了調試,當我嘗試解密(使用相同的代碼)加密的url在app1,它工作正常。但無法弄清楚在app2上導致這個異常的原因是什麼?
下面是代碼
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
public class AESEncryptionDecryptionTest {
private static final String ALGORITHM = "AES";
private static final String myEncryptionKey = "ThisIsFoundation";
private static final String UNICODE_FORMAT = "UTF8";
public static String encrypt(String valueToEnc) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.ENCRYPT_MODE, key);
byte[] encValue = c.doFinal(valueToEnc.getBytes());
String encryptedValue = new BASE64Encoder().encode(encValue);
return encryptedValue;
}
public static String decrypt(String encryptedValue) throws Exception {
Key key = generateKey();
Cipher c = Cipher.getInstance(ALGORITHM);
c.init(Cipher.DECRYPT_MODE, key);
byte[] decordedValue = new BASE64Decoder().decodeBuffer(encryptedValue);
byte[] decValue = c.doFinal(decordedValue);//////////LINE 50
String decryptedValue = new String(decValue);
return decryptedValue;
}
private static Key generateKey() throws Exception {
byte[] keyAsBytes;
keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
return key;
}
public static void main(String[] args) throws Exception {
String value = "password1";
String valueEnc = AESEncryptionDecryptionTest.encrypt(value);
String valueDec = AESEncryptionDecryptionTest.decrypt(valueEnc);
System.out.println("Plain Text : " + value);
System.out.println("Encrypted : " + valueEnc);
System.out.println("Decrypted : " + valueDec);
}
}
見我答,並得到一些想法[這裏同樣的問題] [1] [1]:http://stackoverflow.com/questions/17234359/javax-crypto-illegalblocksizeexception -input-length-must-multiple-of-16-whe/21378212#21378212 希望能對你有所幫助。 – Krishna