0

I'm having some trouble decrypting strings. The error I am recieving is:

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

Here is what I am trying to achieve.

-The user sets a password when creating an account. In this case Taylor.

-This password manager class will translate this string into Gibberish (This is what it produces : "I^ÇÔµoü|& ÄŠóÁ").

-Im then storing this gibberish in a text file.

-From there when the password Taylor is entered this stored gibberish gets decrypted and then compared to the string entered. if its correct the user can access the application.

Thank you for helping.

As a side note i'm not sure if I've initialized the key correctly either :/ This is also my first time playing around with encryption. Im not sure if its really really cool or really really frustrating.

public static void Decrypt(String encryptedText) {
    try 
    {
        //we are using the same key to decrypt the string as we used to encrypt it.
        String key = "AbCd1234aBcD4321";

        // Here we are taking the 128 bit key we just created and expanding it
        Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, aesKey);

        //decrypt the text
        byte[] encrypted = cipher.doFinal(encryptedText.getBytes());   
        String decrypted = new String(cipher.doFinal(encrypted));
        System.out.println(decrypted);

    }
    catch(Exception e) 
    {
        e.printStackTrace();
    }
  • Hi, perhaps create a new cipher stream when attempting to decrypt. Here's an [example](https://stackoverflow.com/questions/15554296/simple-java-aes-encrypt-decrypt-example). – jspcal May 02 '19 at 21:43
  • 1
    Why are you **double** decrypting the input? --- BTW: Encrypted data is *binary*, not text, unless somehow encoded as text (Hex, Base64, ...). – Andreas May 02 '19 at 22:17
  • @James Taylor Could you share your encrypt method? I think the problem is the way you are trying to get the bytes from the encryptedText string parameter. It actually depends on how the output String is being generated from the byte array you get from cipher. – admlz635 May 02 '19 at 22:22

1 Answers1

0

Your issue is this line:

byte[] encrypted = cipher.doFinal(encryptedText.getBytes()); 

You can't convert arbitrary binary information to a string and expect it to convert back correctly. It simply doesn't work that way.

UTF-8 is structured binary data in the same way that an MP3 file is. Not every sequence of bytes produces a valid MP3 file, not every sequence of bytes produces a valid UTF-8 string.

Encrypted data is, by definition, binary data. You should be storing it as such.

Luke Joshua Park
  • 9,527
  • 5
  • 27
  • 44