I have two classes, one is main class and another is the implementation of AES.
However, in my AES class i have a method to decrypt a string, but whenever i run it, it gives an exception
My encryption method works just fine but my decryption method doesn't work as expected.
The code
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;
}
The error this method outputs is
InvalidKeyException java.security.InvalidKeyException: No installed provider supports this key: (null)
UPDATE #1:
So i have updated the code as the following
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;
}
and in the main class i have this line
byte [] byteciphertext = ciphertext.getBytes();
just to convert the string to bytes
is it correct? i'm still having
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
Could someone help me fix this issue?
Thank you.
secretKey
is clearly null.
Other problems:
cipherText
.cipherText
should be a byte[],
not a String
: cipher text is binary, and String
is not a container for binary data.strDecryptedText
should be a local variable, not a member variable.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With