title: Encrypt/Decrypt output buffer size and When to call EVP_EncryptUpdate multiple times
body: <p>I am trying to use openssl to encrypt/decrypt message using AES. 
  After coming through the following study:
  <a href="https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption" rel="noreferrer">https://wiki.openssl.org/index.php/EVP_Symmetric_Encryption_and_Decryption</a>
  <a href="http://www.itc.edu.kh/bib/ebook/storage/Network%20Security%20with%20OpenSSL.pdf" rel="noreferrer">http://www.itc.edu.kh/bib/ebook/storage/Network%20Security%20with%20OpenSSL.pdf</a>   (Chapater 6)</p>
  
  <p>I can encrypt/decrypt successfully. </p>
  
  <p>My scenario is like:</p>
  
  <blockquote>
    <ol>
    <li>Encrypt : Input plain text => encrypt with aes 256 cbc => return result in encode with base64</li>
    <li>Decrypt: Input encrypted base64 encoded string => decode base64 => decrypt with aes 256 cbc => return decrypted plain text</li>
    </ol>
  </blockquote>
  
  <p>But i have some of the question:</p>
  
  <blockquote>
    <ol>
    <li><p>How to allocate the encrypted buffer size:    char *out = (char *) malloc(inLength + EVP_MAX_BLOCK_LENGTH);    Is this enough? I admit
    that i didn't goes through the detail of encryption logic even though
    i have some concept. If someone can give me a hint of the size of
    encrypted size logic, i really be appreciate.  Like base64 data to
    data ratio is 4:3. It has 33% overhead. But for encryption, i don't
    find this kind of information.</p></li>
    <li><p>How to allocate the decrypted buffer size:    b64decodeLen = decode b64 encrypted text. It should the original binary encrypted
    data length.     char *out = (char *) malloc(b64decodeLen + 1);<br>
    According to the above malloc of encrypted buffer size. I think the
    plain text size would be less than the binary encrypted data length. 
    Is this right?</p></li>
    <li><p>EVP_EncryptUpdate can be called multiple times if necessary. When to call multiple times? In which case we need to call multiple times? 
    <a href="https://stackoverflow.com/questions/29016193/block-cipher-in-openssl-how-to-correct-crypt-and-decrypt-in-c">https://stackoverflow.com/questions/29016193/block-cipher-in-openssl-how-to-correct-crypt-and-decrypt-in-c</a></p></li>
    </ol>
  </blockquote>
  
  <pre><code>while(1){
      EVP_EncryptUpdate(ctx, ciphertext + outlen_tot, &amp;outlen, (unsigned   char*)msg + outlen_tot, block_size);
      outlen_tot += outlen;
      if( msg_len - outlen_tot &lt; block_size ){
          break;
      }
  }
  </code></pre>
  
  <blockquote>
    <p>In this example, it encrypt for the block_size. If i put the input
    string length, then i don't need to call multiple times even for every
    large message?</p>
  </blockquote>
  
  <pre><code>EVP_EncryptUpdate(ctx, out, &amp;out_len, inString, strlen(inString));
  </code></pre>
  
  <p>Thanks a lot.</p>