Search code examples
javaencryptionaesapache-commons

Able to decrypt an encrypted text in Java despite changing the encrypted text


I have the following code:

public static void main(final String[] args) throws Exception {
        try {
            String textToEncrypt = "{asdfsad asdf;ls kasdf asdlfjaslfjalksdfjlkadsjflkasfjl;kasj alkdfjaslkfj \r\n" +
                    "asdfjl;asdfjlasdjfdasfjfdosafjadsf \r\n" +
                    "as;ldfjal;ksfjlkdasfjadsf" +
                    "a;ldfjal;ksfjds" +
                    "}";
            String secret = "SOME_SECRET";

        String escapedTextToEncrypt = StringEscapeUtils.escapeJava(textToEncrypt);
        System.out.println(escapedTextToEncrypt);

        String encryptedText = SomeEncryption.encrypt(escapedTextToEncrypt, secret);

        encryptedText = encryptedText.concat("3asdasfd");  // CHANGING THE ENCRYPTED TEXT!

            System.out.println("Encrypted Text :" + encryptedText);

            System.out.println("Decrypted Text :" + SomeEncryption.decrypt(encryptedText, secret));  // THIS WORKS!!
        }catch(Throwable t){
            t.printStackTrace();
        }
    }

I am using AES encryption algorithm and apache commons codec. Curiously, when I append a string to the encrypted text, it is still able to decrypt it with no problems. Am I missing something here?

More details:

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2withHmacSHA1");
SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

EDIT:

I am using StringEscapeUtils from apache commons lang library.


Solution

  • We found the answer to this question. If I add any string at the end of the encrypted string then it works. But if it is inserted in the middle then it fails.

    encryptedText = new StringBuilder(encryptedText).insert(0, "xyz").toString();
    

    The above fails.