错误描述
jdk版本:8
加解密算法采用DES,转换模式为 DES/CBC/PKCS5Padding,在进行解密时,报如下错误
Exception in thread "main" java.security.InvalidKeyException: Parameters missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:469)
at com.sun.crypto.provider.DESCipher.engineInit(DESCipher.java:186)
at javax.crypto.Cipher.implInit(Cipher.java:801)
at javax.crypto.Cipher.chooseProvider(Cipher.java:863)
at javax.crypto.Cipher.init(Cipher.java:1248)
at javax.crypto.Cipher.init(Cipher.java:1185)
at com.example.jcrypt.service.impl.DesDemoImpl.decrypt(DesDemoImpl.java:75)
at com.example.jcrypt.service.impl.DesDemoImpl.jdk8Des(DesDemoImpl.java:50)
at com.example.jcrypt.service.impl.DesDemoImpl.main(DesDemoImpl.java:37)
原因分析
CBC模式下的DES,得有初始化向量
解决方法
/**
* @param secretKey 密钥对象
* @param data 加密后的base64字符串
*/
private void decryptEnhance(SecretKey secretKey, String data) throws NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, IllegalBlockSizeException, InvalidKeyException, InvalidAlgorithmParameterException {
byte[] decodeBytes = Base64.getDecoder().decode(data);
Cipher cipher = Cipher.getInstance(TRANSFORM);
byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0};
IvParameterSpec ivspec = new IvParameterSpec(iv);
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivspec);
byte[] bytes = cipher.doFinal(decodeBytes);
log.info("DES 解密后base64为:{},IV值:{}", new String(bytes), cipher.getIV());
}
注意:
- 字节数组长度是8位字节
- 解密和加密的iv字节数组,必须一样。否则,中文解密乱码。
参考文章
https://blog.csdn.net/quantum7/article/details/120413141
https://rumenz.com/java-topic/security/invalidkeyexception-parameters-missing/index.html