Correct way to use php openssl_encrypt : <p>I'm working with cryptography on a project and I need a little help on how to work with <code>openssl_encrypt</code> and <code>openssl_decrypt</code>, I just want to know the most basic and correct way to do it. Here is what I got so far:</p>

<pre><code>// To encrypt a string

$dataToEncrypt = 'Hello World';

$cypherMethod = 'AES-256-CBC';
$key = random_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cypherMethod));

$encryptedData = openssl_encrypt($dataToEncrypt, $cypherMethod, $key, $options=0, $iv);
</code></pre>

<p>I then store <code>$cypherMethod</code>, <code>$key</code>, and <code>$iv</code> for use when decrypting the <code>$encryptedData</code>. <em>(Let's not elaborate how I store the values, thanks!)</em></p>

<pre><code>// To decrypt an encrypted string

$decryptedData = openssl_decrypt($encryptedData, $cypherMethod, $key, $options=0, $iv);
</code></pre>

<hr>

<p>First off, is the above example code a correct example of how to use <code>php openssl_encrypt</code>?</p>

<p>Second, is my method to generate the <code>$key</code> and <code>$iv</code> correct and secure? Because I keep on reading, keys should be cryptographically secure.</p>

<p>Lastly, isn't a <code>32-byte</code> value required for <code>AES-256-CBC</code>? If yes, then why is it that <code>openssl_cipher_iv_length()</code> returns only <code>int(16)</code> as the length? Shouldn't it be <code>int(32)</code>?</p>
