AES CBC 会截断长度超过 16 个字符的字符串。下次运行时,它显示 javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
UPD:这是有问题的代码:
public static byte[][] encrypt(String txt, String txt2, String txt3){
try {
SecretKey mysecretKey = new SecretKeySpec("qwertyuiopasdfgh".getBytes(), "AES");
byte[] plainText1 = txt.getBytes();
byte[] plainText2 = txt2.getBytes();
byte[] plainText3 = txt3.getBytes();
byte[][] plain_bytes = new byte[][] { plainText1, plainText2, plainText3 };
IvParameterSpec iv = new IvParameterSpec("4283810222669651".getBytes());
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, mysecretKey, iv);
cipher.update(plainText1);
byte[] cipherText1 = cipher.doFinal();
cipher.update(plainText2);
byte[] cipherText2 = cipher.doFinal();
cipher.update(plainText3);
byte[] cipherText3 = cipher.doFinal();
byte[][] encrypted_bytes = new byte[][] { cipherText1, cipherText2, cipherText3 };
String str = Base64.getEncoder().encodeToString(encrypted_bytes[0]);
encryptedUrl = str;
System.out.println(encryptedUrl);
return encrypted_bytes;
} catch (Exception e1) {
e1.printStackTrace();
return null;
}
}
不,@Enikeyshchik,这里的一切都比较棘手。
TC 试图通过使用多部分编码
cipher.update()/doFinal()并且做错了。你只需要对
doFinal()你的每一件作品应用这样的东西:AES 以 128 位的块进行加密(也就是说,这些是您的 16 个字节)。错误告诉你最后一个块小于这个大小,需要填充一些东西才能达到 128 位。