-2

I tried to encrypt the JSON in javascript as shown in below and it is encrypted. In below "obj" is my JSON data and i don't know why "ency_key", I followed this from some where in google and they passed String like that.

var obj1 = CryptoJS.AES.encrypt(obj,'ency_key').toString();
$.ajax({
    url: "web/enyDcyData", 
    "type": "POST",
    async:true,
    data:{   
        json:obj1,
    }

but am unable to decryption the data in java, I tried like below in java. am getting javax.crypto.BadPaddingException: Given final block not properly padded exception at "doFinal(base64Decode(ency_data));" where I done mistake, please help me to solve this problem.

public static String decrypt(String ency_data)
        SecretKeyFactory keyFac = SecretKeyFactory.getInstance(one);
        SecretKey seckey = keyFac.generateSecret(new PBEKeySpec(two));
        Cipher cipher = Cipher.getInstance(one);
        pbeCipher.init(Cipher.DECRYPT_MODE, seckey , new PBEParameterSpec(SALT, 20));
        byte[] res = cipher.doFinal(base64Decode(ency_data));
        String decryptedValue = new String(res,"UTF-8");
    }   

        private static byte[] base64Decode(String ency_data) throws IOException {
           return new BASE64Decoder().decodeBuffer(ency_data);
        }
NRV
  • 17
  • 8
  • 1
    _"I tried different ways in java but am getting different error"_ Then show them (at least one of them) – Andreas Dec 15 '17 at 14:26
  • From your comments, it sounds like you don't know what key is being used on the JavaScript side, so you can't even check whether you're getting the same key from `keyFac.generateSecret()` on the Java side. I would think the basic prerequisite for asking a crypto question on SO would be to be able to verify that the key you're using for encryption on the JavaScript side is the same key you're using on the Java side to decrypt. Your output is consistent with using different keys (as well as many other errors)...if you can't rule that out, we can't really help you. Does `one` even select AES? – lockcmpxchg8b Dec 15 '17 at 22:25

1 Answers1

1

The key derivation function you are using is different. CryptoJS (version 3) uses an OpenSSL compatible key derivation function, while you are using PBKDF1 (or possibly 2, your algorithm isn't included). You may need to look for an implementation of EVP_BytesToKey, e.g. here. Or you could look for an entire OpenSSL compatibility layer, of course.

If the key or data differs then you should expect a padding error for CBC / ECB mode; it's the only error that can be thrown if the data size is a multiple of the block size (and the key / algorithm have been accepted during instantiation / inititialization).

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263