JAVA AES加解密在Linux报错javax.crypto.BadPaddingException: Given final block not properly padded.
linux-dash
A beautiful web dashboard for Linux
项目地址:https://gitcode.com/gh_mirrors/li/linux-dash
免费下载资源
·
在Windows加解密都正常,在linux中解密失败,报错javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
报错的代码
private Key initKeyForAES(String key) throws NoSuchAlgorithmException {
if (null == key || key.length() == 0) {
throw new NullPointerException("key not is null");
}
SecretKeySpec key2 = null;
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, new SecureRandom(key.getBytes()));//该行在linux下出现问题
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
key2 = new SecretKeySpec(enCodeFormat, "AES");
} catch (NoSuchAlgorithmException ex) {
throw new NoSuchAlgorithmException();
}
return key2;
}
修改代码为:
private Key initKeyForAES(String key) throws NoSuchAlgorithmException {
if (null == key || key.length() == 0) {
throw new NullPointerException("key not is null");
}
SecretKeySpec key2 = null;
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");//修改后
random.setSeed(key.getBytes());
try {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128, random);
SecretKey secretKey = kgen.generateKey();
byte[] enCodeFormat = secretKey.getEncoded();
key2 = new SecretKeySpec(enCodeFormat, "AES");
} catch (NoSuchAlgorithmException ex) {
throw new NoSuchAlgorithmException();
}
return key2;
}
原因:
SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法,然后调用 setSeed 方法;该实现在 windows 上每次生成的 key 都相同,但是在 solaris 或部分 linux 系统上则不同。关于SecureRandom类的详细介绍,见 http://yangzb.iteye.com/blog/325264
参考链接:
https://www.cnblogs.com/zempty/p/4318902.html
https://blog.csdn.net/rj042/article/details/8196125
GitHub 加速计划 / li / linux-dash
10.39 K
1.2 K
下载
A beautiful web dashboard for Linux
最近提交(Master分支:2 个月前 )
186a802e
added ecosystem file for PM2 4 年前
5def40a3
Add host customization support for the NodeJS version 4 年前
更多推荐
已为社区贡献2条内容
所有评论(0)