title: AES Encrypt using CryptoJS
body: <p>I need to implement AES encryption using JavaScript. Used AES/CBC/NoPadding Mode and created a method to complete 16 lenght blocks. I already solved it using Java. It looks like:</p>
  
  <pre><code>public static String encrypt(byte[] key, byte[] initVector, String value) {
      try {
          IvParameterSpec iv = new IvParameterSpec(initVector);
          SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");
          Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
          cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
          byte[] encrypted = cipher.doFinal(completeBlocks(value));
          return Base64.encodeBase64String(encrypted);
      } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException ex) {
          System.out.println("Error: " + ex);
      }
  
      return null;
  }
  
  /**
   * Completes 16 lenght blocks
   *
   * @param message
   *
   *
   */
  static byte[] completeBlocks(String message) {
      try {
  
          int bytesLenght = message.getBytes("UTF-8").length;
          if (bytesLenght % 16 != 0) {
              byte[] newArray = new byte[bytesLenght + (16 - (bytesLenght % 16))];
              System.arraycopy(message.getBytes(), 0, newArray, 0, bytesLenght);
              return newArray;
          }
  
          return message.getBytes("UTF-8");
  
      } catch (UnsupportedEncodingException ex) {
          System.out.println("" + ex);
      }
      return null;
  }
  
  public static void main(String[] args) {
  
      String key = "253D3FB468A0E24677C28A624BE0F939";
      String strToEncrypt = "My Secret text";
      final byte[] initVector = new byte[16];
      String resultado = encrypt(new BigInteger(key, 16).toByteArray(), initVector, strToEncrypt.trim());
      System.out.println("ENCRYPTED:");
      System.out.println(resultado);
  }
  </code></pre>
  
  <p>With inputs <code>key = 253D3FB468A0E24677C28A624BE0F939</code>, <code>strToEncrypt = "My Secret text"</code> and ceros IV. It throws </p>
  
  <blockquote>
    <p>7StScX3LnPUly/VNzBes0w==</p>
  </blockquote>
  
  <p>I Know it's the desired output. It's right!
  I tried to replicate this using JavaScript. I used CryptoJs library. But i wasn't able to produce same Java's output. I have tryed:</p>
  
  <pre><code>var text = "My Secret text";
  var key = CryptoJS.enc.Base64.parse("253D3FB468A0E24677C28A624BE0F939");
  var iv  = CryptoJS.enc.Base64.parse("                ");
  var encrypted = CryptoJS.AES.encrypt(text, key, {iv: iv});
  console.log(encrypted.toString());
  
  var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv});
  console.log(decrypted.toString(CryptoJS.enc.Utf8));
  </code></pre>
  
  <p>Using the same inputs, i get <code>De+CvPVIyiBX2//EE6gXTg==</code> as output. What am I doing wrong? How can i get same Java's output? Thanks a lot!!</p>