Question

I am trying to encrypt the password sent by the client side using Javascript's CryptoJS and decrypt it on the server side using Java's Cipher class.

On Client Side :

<html>
<body>
    <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/aes.js"></script>
    <script src="http://crypto-js.googlecode.com/svn/tags/3.1/build/components/pad-nopadding.js"></script>
    <script>
        var iv  = CryptoJS.enc.Hex.parse('101112131415161718191a1b1c1d1e1f');
        var encrypted = CryptoJS.AES.encrypt("A Sample Message", "SecretPassphrase", { mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.NoPadding, iv: iv });
        console.log("iv: " + encrypted.iv.toString(CryptoJS.enc.Hex));
        console.log("ct: " + encrypted.ciphertext.toString(CryptoJS.enc.Hex));
    </script>
</body>
</html>

The output i am getting on Firebug is

iv: a43e384b24e275c29a8a68bc031fd79e
ct: c86b6ca4ef30fadfea28821e04aa8dad

On server side :

import java.nio.charset.Charset;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.*;

public class AES {

    public static String decrypt(String encryptedData) throws Exception {
        byte[] keyBytes = "SecretPassphrase".getBytes();
        Key key = new SecretKeySpec(keyBytes, "AES");

        Cipher c = Cipher.getInstance(ALGO);

        byte[] iv = (byte[]) new Hex().decode("a43e384b24e275c29a8a68bc031fd79e");
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        c.init(Cipher.DECRYPT_MODE, key, ivspec);

        byte[] decordedValue = (byte[]) new Hex().decode(encryptedData);
        byte[] decValue = c.doFinal(decordedValue);

        String decryptedValue = Hex.encodeHexString(decValue);
        return decryptedValue;
    }

    public static void main(String[] args) throws Exception {
        String result = AES.decrypt("c86b6ca4ef30fadfea28821e04aa8dad");
        System.out.println(hexToString(result));
    }
}

I need some help about what i am doing wrong and why am i getting random iv on my client side when i am restricting it to use passed iv.

Was it helpful?

Solution

You are passing a passphrase instead of a key at the client side. So it will do OpenSSL key derivation, probably generating an IV in there as well.

Performing SecretPassphrase".getBytes() is something that you should never do either. Use hexadecimals if you want your key to be text, and convert it into binary using hexadecimal decoding.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top