title: cryptojs aes 256 encryption and java decryption
body: <p>I encrypted message with cryptojs aes 256 on the client side. But couldn't decrypt it on the java side. First, I pass the key directly to the server side as hex, then convert it from hex to java bytearray. It didn't work. Then I pass the phrase, salt, iv to the server as hex. Then generate the key. It still didn't work. It always to complain the key length is not right.</p>
  
  <p>Client side:</p>
  
  <pre><code>var salt = CryptoJS.lib.WordArray.random(16);
  var salt_hex = CryptoJS.enc.Hex.stringify(salt);
  
  var iv = CryptoJS.lib.WordArray.random(256/32);
  var iv_hex = CryptoJS.enc.Hex.stringify(iv);
  
  
  var key = CryptoJS.PBKDF2(secret, salt, { keySize: 256/32, iterations: 10 });
  var key_hex=CryptoJS.enc.Hex.stringify(key);
  
  var encrypted = CryptoJS.AES.encrypt(plaintext, key, { iv: iv });    
  
  var encryptedtxt = secret+":"+salt_hex+":"+iv_hex+":"+encrypted.ciphertext.toString(CryptoJS.enc.Base64)+":"+key_hex;
  </code></pre>
  
  <p>Server side:</p>
  
  <pre><code>    if (encrypted != null)
      {
          //Get the passphras, salt, IV and msg
          String data[] = encrypted.split(":");
          String passphrase = data[0];
          String salt_hex = data[1];
          String iv_hex = data[2];
          String msg64 = data[3];
          String jskey_hex = data[4];
          byte[] jskey = hexStringToByteArray(jskey_hex);
          byte[] iv = hexStringToByteArray(iv_hex);
          byte[] salt = hexStringToByteArray(salt_hex);
          BASE64Decoder decoder = new BASE64Decoder();
          byte[] msg = decoder.decodeBuffer(msg64);
  
          try {
               //theClear = AES.decrypt(encrypted);
              /* Decrypt the message, given derived key and initialization vector. */
              SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
              KeySpec spec = new PBEKeySpec(passphrase.toCharArray(), salt, 10, 256/32);
              SecretKey key = new SecretKeySpec(factory.generateSecret(spec).getEncoded(), "AES");
              Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
              cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
              String plaintext = new String(cipher.doFinal(msg), "UTF-8");
          } catch (Exception e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
  </code></pre>