当我尝试解密时出现以下错误

时间:2019-05-06 08:56:59

标签: java

解密时出现以下错误。

一旦运行正常,但突然我收到此错误。

如何解决此问题? 我读了很多文章,但无法获得帮助。

java.security.InvalidKeyException: Parameters missing
at com.sun.crypto.provider.CipherCore.init(CipherCore.java:388)
at com.sun.crypto.provider.AESCipher.engineInit(AESCipher.java:186)
at javax.crypto.Cipher.implInit(Cipher.java:786)
at javax.crypto.Cipher.chooseProvider(Cipher.java:848)
at javax.crypto.Cipher.init(Cipher.java:1212)
at javax.crypto.Cipher.init(Cipher.java:1152)
at 
com.test.security.TestEncryptDecrypt.decrypt(TestEncryptDecrypt.java:92)
at com.test.security.TestEncryptDecrypt.main(TestEncryptDecrypt.java:59)

代码如下:

public static void main(String []args){

try {

String encString =  encrypt("PID=0000000003|ITC=NA|PRN=MNKB0701511135|AMT=1.00|CRN=INR|RU=https://www.testsite.com/testsk/servlet/TestResponseHandler?");

System.out.println("Enc  : " + encString);

System.out.println("Dec  : "+ decrypt(encString));

} catch (Exception e) {

e.printStackTrace();
}

}

加密方法

public static String encrypt(String data) throws Exception {
String keyFile = "E:\\testpath\\Keys\\0000000003.key";
byte[] keyb = Files.readAllBytes(Paths.get(keyFile));

SecretKeySpec skey = new SecretKeySpec(keyb, "AES");
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, skey);
byte[] encVal = c.doFinal(data.getBytes());
return new BASE64Encoder().encode(encVal);
}

解密方法

public static String decrypt(String encryptedData)
throws InvalidKeyException, IllegalBlockSizeException,
BadPaddingException, NoSuchAlgorithmException,
NoSuchPaddingException, IOException {

String keyFile = "E:\\testpath\\Keys\\0000000003.key";

byte[] keyb = Files.readAllBytes(Paths.get(keyFile));

SecretKeySpec skey = new SecretKeySpec(keyb, "AES");    
Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.DECRYPT_MODE, skey);

byte[] decordedValue = Base64.decodeBase64(encryptedData.getBytes());
byte[] decValue = c.doFinal(decordedValue);
return new String(decValue);
}

1 个答案:

答案 0 :(得分:0)

如错误消息所述,您在init方法中缺少参数。如果您使用的是CBC,还应该指定AlgorithmParameterSpec

您也许可以尝试以下方法:

byte[] paramSpecBytes = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
IvParameterSpec paramSpec = new IvParameterSpec(paramSpecBytes);

在您的加密和解密方法中:

c.init(Cipher.ENCRYPT_MODE, skey, paramSpec);
c.init(Cipher.DECRYPT_MODE, skey, paramSpec);

您可以用任何您喜欢的值来填充字节,而不必为零。最好是一些随机值。