采用aes加密解密时,发现正常在windows下正常运行的功能,部署到linux环境中出现解密报错的情况,报错信息如下:
javax.crypto.BadPaddingException: Given final block not properly padded. Such issues can arise if a bad key is used during decryption.
at com.sun.crypto.provider.CipherCore.unpad(CipherCore.java:975)
at com.sun.crypto.provider.CipherCore.fillOutputBuffer(CipherCore.java:1056)
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:853)
at com.sun.crypto.provider.AESCipher.engineDoFinal(AESCipher.java:446)
经过翻阅资料发现,windows和linux对相同明文加密产生的结果是不同的;其次linux对明文解密过程中会抛出异常。
因此进行了如下修改:
修改前:
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
kgen.init(128, new SecureRandom(password.getBytes()));
修改后:
String charset = "utf-8";
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG") ;
secureRandom.setSeed(password.getBytes(charset));
kgen.init(128, secureRandom);
文章来源: www.oschina.net,作者:高乐钏,版权归原作者所有,如需转载,请联系作者。
原文链接:https://my.oschina.net/u/3786691/blog/3163723