AES加密时报错:IllegalBlockSizeException: Input length not multiple of 16 bytes

报错情况

在使用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);
	}

  • 2
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

knight郭志斌

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值