报错情况
在使用java的Cipher类进行AES加密时,报错:IllegalBlockSizeException: Input length not multiple of 16 bytes
Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length not multiple of 16 bytes
at com.sun.crypto.provider.CipherCore.finalNoPadding(CipherCore.java:1042)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:1010)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:847)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
报错的代码
public static String encrypt2(String content, String slatKey, String vectorKey) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return Base64.encodeBase64String(encrypted);
}
public static void main(String[] args) throws Exception {
String s = encrypt2("Asdfg123456-", "12345b06ee341234", "12345b06ee341234");
System.out.println(s);
}
解决方法
创建Cipher的时:Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding")
使用的是NoPadding不填充的方式,
改用:Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");就可以了。
改正后的代码
public static String encrypt2(String content, String slatKey, String vectorKey) throws Exception {
//改了填充方式
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKey secretKey = new SecretKeySpec(slatKey.getBytes(), "AES");
IvParameterSpec iv = new IvParameterSpec(vectorKey.getBytes());
cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
byte[] encrypted = cipher.doFinal(content.getBytes());
return Base64.encodeBase64String(encrypted);
}
public static void main(String[] args) throws Exception {
String s = encrypt2("Asdfg123456-", "12345b06ee341234", "12345b06ee341234");
System.out.println(s);
}