在windows系统上加密解密都没问题,到了linux服务器上解密失败。
错误信息:javax.crypto.BadPaddingException: Given final block not properly padded
查阅资料得知,问题是出在生成key的方法上:SecureRandom 实现完全随操作系统本身的內部状态,在windows上生成的key每次都是一样的,在linux上生成的不同,所以需要在调用getInstance方法之后再调用setSeed方法。
public static SecretKey getKey (String strKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
kgen.init(128, new SecureRandom(key.getBytes()));
return kgen.generateKey();
} catch (Exception e) {
throw new RuntimeException( " 初始化密钥出现异常 " );
}
}
处理后的代码:
public static SecretKey getKey (String strKey) {
try {
KeyGenerator kgen = KeyGenerator.getInstance(KEY_AES);
//2.根据ecnodeRules规则初始化密钥生成器
//生成一个128位的随机源,根据传入的字节数组
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
return kgen.generateKey();
} catch (Exception e) {
throw new RuntimeException( " 初始化密钥出现异常 " );
}
}