title: CryptoJS to OpenSSL encryption conversion
body: <p>I need to port some JavaScript code to a C99 backend. In the Javascript code they use CryptoJS to perform AES encryption:</p>
  
  <pre><code>var key = CryptoJS.MD5(Math.random().toString()).toString();
  key = CryptoJS.enc.Hex.parse(key);
  
  var iv = CryptoJS.MD5(Math.random().toString()).toString();
  iv = CryptoJS.enc.Hex.parse(iv);
  
  var data = "testdata";
  var encrypted = CryptoJS.AES.encrypt(data, key, { iv:iv, mode:CryptoJS.mode.CBC, padding:CryptoJS.pad.ZeroPadding });
  </code></pre>
  
  <p>Now I need to implement the same code in C with the OpenSSL library. I have created the random MD5 strings without problem but I cannot see how to implement the AES encryption with zero padding. This is what I have:</p>
  
  <pre><code>bool crypto_aes_encrypt(const char* data, unsigned char *key, unsigned char *iv, unsigned char **out_buf, int *out_buf_len)
  {
      ERR_load_crypto_strings();
      OPENSSL_add_all_algorithms_conf();
  
      /* Initialize the cipher context */
      EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
      if(!ctx) {
          return NULL;
      }
  
      /* Initialize the AES encryption */
      if(EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv) != 1) {
          return NULL;
      }
  
      /* Encrypt the data */
      *out_buf = (unsigned char*) malloc(2048 * sizeof(char));
      *out_buf_len = 0;
      if(EVP_EncryptUpdate(ctx, *out_buf, out_buf_len, (const unsigned char*) data, strlen(data)) != 1) {
          free(out_buf);
          return NULL;
      }
  
      if(EVP_EncryptFinal(ctx, *out_buf + *out_buf_len, out_buf_len) != 1) {
          free(out_buf);
          return NULL;
      }
  
      EVP_CIPHER_CTX_free(ctx);
      EVP_cleanup();
      ERR_free_strings();
  
      return true;
  }
  </code></pre>
  
  <p>How can I implement the ZeroPadding in OpenSSL which is used in CryptoJS?</p>