javax.crypto.BadPaddingException: Given final block not properly padded

时间:2021-06-14 04:56:42

一、报错

写了一个加密方法,在Windows上运行没有问题,在Linux上运行时提示如下错误:

javax.crypto.BadPaddingException: Given final block not properly padded

二、定位

查找资料,得到原因:

 SecureRandom实现完全随操作系统本身的內部状态。
该实现在 windows 上每次生成的 key 都相同。
但是在 solaris 或部分 linux 系统上则不同。

通过日志打印,证实了这一点。

三、解决

资料里还有这么一句:

SecureRandom ...除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法。

原代码如下:

secureRandom = new SecureRandom(seed.getBytes());

修改后的代码如下:

 SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(seed.getBytes());

在Linux上再次运行测试,不报错了。问题解决。