使用tomcat,我有两个web应用程序,即app1和app2.我将app1以加密形式(使用下面的代码)发送到app2.然后在app2我解密了这个加密的网址.但是我在decryp方法的第50行低于例外.
"Getting javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher"
Run Code Online (Sandbox Code Playgroud)
虽然我尝试在app1解密(使用相同代码)加密的URL时进行调试,但它工作正常.但无法弄清楚在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);
}
}
Run Code Online (Sandbox Code Playgroud)
emb*_*oss 11
适用于我的机器.如果在将字节转换为字符串的每个实例中使用`UNICODE_FORMAT',反之亦然,这会有帮助吗?这条线可能是一个问题:
byte[] encValue = c.doFinal(valueToEnc.getBytes());
Run Code Online (Sandbox Code Playgroud)
应该
byte[] encValue = c.doFinal(valueToEnc.getBytes(UNICODE_FORMAT));
Run Code Online (Sandbox Code Playgroud)
无论如何,如果您使用"AES"作为算法并使用JCE,则实际使用的算法将是"AES/ECB/PKCS5Padding".除非您100%确定自己在做什么,否则不应将ECB用于任何事情.我建议总是明确指定算法,以避免这种混淆."AES/CBC/PKCS5Padding"将是一个不错的选择.但请注意,使用任何合理的算法,您还必须提供和管理IV.
在加密密码的情况下,使用ECB密码甚至是不太理想的,如果我正确地解释您的示例,这就是您在加密时所做的事情.您应该使用PKCS#5中为此目的指定的基于密码的加密,在Java中,这是在SecretKeyFactory中为您提供的.确保使用"PBKDF2WithHmacSHA1"具有足够高的迭代次数(任何范围从~5-20000,取决于您的目标机器),以使用密码从它们派生对称密钥.
如果它实际上是密码存储而不是密码加密,那么可以使用相同的技术.