Search code examples
javaencryptioncryptographycryptojs

How to decrypt on the server side with java code?


I am using CryptoJS to encrypt at the client side I have created a fiddle of the client side code as following -

var onClick = function() {
   var iv = "3ad5485e60a4fecde36fa49ff63817dc"; 

            var key = "0a948a068f5d4d8b9cc45df90b58d382d2b916c25822b6f74ea96fe6823132f4"; 

            var encrypted = CryptoJS.AES.encrypt("{'This is ' : 'A Nice day'}",
                    key, {
                        iv : CryptoJS.enc.Hex.parse(iv),
                        mode : CryptoJS.mode.CBC,
                        padding : CryptoJS.pad.Pkcs7
                    }); 
            var encryptedInHex = encrypted.ciphertext
                    .toString(CryptoJS.enc.Hex); // converting the encrypted data in Hexadecimal
    document.getElementById("thisDiv").innerHTML  = encryptedInHex.toUpperCase();
            return encryptedInHex.toUpperCase(); // returning the hashed encrypted data.
};

I have also developed a fiddle for it here -

http://jsfiddle.net/akki166786/1c24d1mj/3/

This is symmetric key cryptography being used here.

when I am trying to decrypt it on server side I am getting,

javax.Crypto.BadPaddingException : Given final block not properly padded exception,

Can there be a problem from Client side as well?

I need a server side(written in java) code to decrypt the out put of the function which i Have written in fiddle.

Thanks for your help.


Solution

  • You'll find the Java code to decrypt the ciphertext below. A couple of notes first:

    • server-side code uses commons-codec for hex decoder
    • in client-side code, replace key parameter to encrypt function with CryptoJS.enc.Hex.parse(key)

    That should be it. And now the code ...

    public class Decryptor {
    
        private static final String IV = "3ad5485e60a4fecde36fa49ff63817dc";
        private static final String KEY = "0a948a068f5d4d8b9cc45df90b58d382d2b916c25822b6f74ea96fe6823132f4";
        private final static String CIPHERTEXT = "4E6B9EC6B5A0614BF9D69C5B0B5AE03D27484F2DB9D450E50EE623E80B8E34F5";
    
        public static final void main(String[] args) throws DecoderException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException {
            SecretKeySpec sks = new SecretKeySpec(Hex.decodeHex(KEY.toCharArray()), "AES");
            IvParameterSpec iv = new IvParameterSpec(Hex.decodeHex(IV.toCharArray()));
            Cipher c = Cipher.getInstance("AES/CBC/NoPadding");
            c.init(Cipher.DECRYPT_MODE, sks, iv);
            byte[] plain = c.doFinal(Hex.decodeHex(CIPHERTEXT.toCharArray()));
            String plainText = new String(plain);
            System.out.println(plainText);
        }
    }