我有两个类,一个是主类,另一个是AES的实现.
但是,在我的AES类中,我有一种解密字符串的方法,但是每当我运行它时,它都会产生异常
我的加密方法工作正常,但我的解密方法无法正常工作.
编码
private Cipher aesCipherForDecryption;
String strDecryptedText = new String();
public String decryptAES(final String ciphertext) {
try {
aesCipherForDecryption = Cipher.getInstance("AES/CBC/PKCS5PADDING");
aesCipherForDecryption.init(Cipher.DECRYPT_MODE, secretKey, new IvParameterSpec(iV));
byte[] byteDecryptedText = aesCipherForDecryption.doFinal(byteCipherText);
strDecryptedText = new String(byteDecryptedText);
} catch (IllegalBlockSizeException e) {
System.out.print("IllegalBlockSizeException " +e);
} catch (BadPaddingException e) {
System.out.print("BadPaddingException "+e);
} catch (NoSuchAlgorithmException e) {
System.out.print("NoSuchAlgorithmException "+ e);
} catch (NoSuchPaddingException e) {
System.out.print("NoSuchPaddingException "+e);
} catch (InvalidKeyException e) {
System.out.print("InvalidKeyException "+e);
} catch (InvalidAlgorithmParameterException e) {
System.out.print("InvalidAlgorithmParameterException "+e);
}
System.out.println("\nDecrypted Text message is " + strDecryptedText);
return strDecryptedText;
}
该方法输出的错误是
InvalidKeyException java.security.InvalidKeyException: No installed provider supports this key: (null)
更新#1:
所以我更新了以下代码
public String decryptAES(byte[] ciphertext) {
String strDecryptedText = new String();
try {
byte[] byteDecryptedText = aesCipherForDecryption.doFinal(ciphertext);
strDecryptedText = new String(byteDecryptedText);
} catch (IllegalBlockSizeException e) {
System.out.print("IllegalBlockSizeException "+e);
e.printStackTrace();
} catch (BadPaddingException e) {
System.out.print("BadPaddingException "+e);
e.printStackTrace();
}
System.out.println("\nDecrypted Text message is " + strDecryptedText);
return strDecryptedText;
}
在主班我有这条线
byte [] byteciphertext = ciphertext.getBytes();
只是将字符串转换为字节
这是正确的吗?我还有
IllegalBlockSizeException javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipherjavax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
有人可以帮我解决这个问题吗?
谢谢.
解决方法:
secretKey显然为null.
其他问题:
>您没有使用输入参数cipherText.
>输入参数cipherText应该是byte [],而不是字符串:密文是二进制的,并且String不是二进制数据的容器.
>结果字符串strDecryptedText应该是局部变量,而不是成员变量.