本文主要是介绍javax.crypto.BadPaddingException: Given final block not properly padded解决方案,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
JAVA的AES加密解密在windows上测试一切正常,上传到空间上在解密时就出现错误。空间是Linux系统
查看日志发现出现此异常
javax.crypto.BadPaddingException: Given final block not properly padded
后面百度了一下终于解决了,在生成key的时候出现错误的
原来的代码:
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()));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创建的方式不同而引起的错误,具体原理我也不懂,因为加密解密代码都是网上搜的,具体没研究过这个。总之能解决问题就好。
我是从这找到解决方案的:http://wenku.baidu.com/link?url=wOibKHENi2Z5gFOL5prjGBE8RES1dZEZlrvfY1NTl89QJWtTwXUNLmgEXVYWGBGXR25oRvOKPJTI5M3o95KW0yIHwgFVEnJiZt1-0YvRQua
随心地记录一些东西,以备不时之需。
这篇关于javax.crypto.BadPaddingException: Given final block not properly padded解决方案的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!