在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