0

I was able to successfully encrypt a message with a generated key. Now I am trying to achive decryption whereby a user would enter a key (hex) and there encrypted message (hex). I am having a problem when decrypting the the encrypted message (hex). I receive multiple NullPointerExceptions. Could you possible help me figure out a solution to this problem please?

//Edit: For Example the key (Hex): CFDD0F5311764F9EA56CF4126E304BC2 | Encrypted Message: C2A80A2B7A84A5A785E059F19322E5BA

private void executeDecryption() {
    encryptMessageStr = messageEncryptTA.getText();
    algorithmType = decryptAlgorithmTypeCB.getSelectionModel().getSelectedItem();
    keyDecrypt = keyTF.getText();

    if (!messageEncryptedTA.getText().isEmpty()) {

        try {
            //Using decryptText()
            String textDecipher = decryptText(encryptedMessageStr, keyDecrypt);
            messageEncryptedTA.setText(textDecipher);

        } catch (Exception ex) {
            MessageBox.display("Error!", "Could not decrypt message! Please try again later");
            //System.out.println(ex.getMessage());
        }

    } else {
        MessageBox.display("Warning!", "Please make sure message field is not empty!");
    }
}

public static String decryptText(String encryptedMessageStr, String secretKey) {
    try {
        Key k = new SecretKeySpec(Base64.getDecoder().decode(secretKey), "AES");
        Cipher cipherAES = Cipher.getInstance("AES");
        cipherAES.init(Cipher.DECRYPT_MODE, k);

        byte[] decodedValue = Base64.getDecoder().decode(encryptedMessageStr);
        byte[] cipherTextBytes = cipherAES.doFinal(decodedValue);
        String decryptedValue = new String(cipherTextBytes);
        return decryptedValue;

    } catch (Exception ex) {
        ex.printStackTrace();
    }

    return "Error";

}

Edited:

EXCEPTION: javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher

Milan
  • 763
  • 3
  • 10
  • 18

1 Answers1

0

Without any context or line numbers it is difficult to pinpoint the exact problem. You should check where in your code the exception is thrown and why the variable you're trying to access is null. Also check this question, as suggested by Simze

According to the Base64.Decoder documentation,

Unless otherwise noted, passing a null argument to a method of this class will cause a NullPointerException to be thrown.

So you are somehow passing a null String reference to the decode method.

Community
  • 1
  • 1
  • Hello, I have added some edits to the Null pointer Exceptions. – Milan Jul 21 '16 at 10:29
  • Your mostlikely correct. The problem is the fact that I am taking in a hex value when I supossed to be taking a plain text. Any ideas on how i can covert the hex into bytes? – Milan Jul 21 '16 at 10:58
  • How do I convert a string(hex) to the seceret key? – Milan Jul 21 '16 at 11:56