windows 加解密正常,linux 下解密失败。报以下错误:
javax.crypto.BadPaddingException: Given final block not properly padded
问题点出现在密钥生成上:
代码如下:
protected SecretKeySpec genSecretKeySpec() throws DubheException{ if (getPs() == null) { throw new DubheException("未配置密钥!"); } KeyGenerator kgen = null; try { kgen = KeyGenerator.getInstance(getAlgorithm()); kgen.init(getKeyLen(), new SecureRandom(getPs().getBytes())); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, getAlgorithm()); return key; } catch (NoSuchAlgorithmException e) { throw new DubheException("未找到算法类型!", e); } }
此方式表现为:在windows 下密钥生成不变,在linux下生成变化的密钥,导致解密失败。
改成如下方式问题得到解决:
@Override protected SecretKeySpec genSecretKeySpec() throws DubheException{ if (getPs() == null) { throw new DubheException("未配置密钥!"); } KeyGenerator kgen = null; try { kgen = KeyGenerator.getInstance(getAlgorithm()); SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG"); secureRandom.setSeed(getPs().getBytes());; kgen.init(getKeyLen(), secureRandom); SecretKey secretKey = kgen.generateKey(); byte[] enCodeFormat = secretKey.getEncoded(); SecretKeySpec key = new SecretKeySpec(enCodeFormat, getAlgorithm()); return key; } catch (NoSuchAlgorithmException e) { throw new DubheException("未找到算法类型!", e); } }
原因分析:
SecureRandom 实现完全随操作系统本身的內部状态,除非调用方在调用 getInstance 方法之后又调用了 setSeed 方法;