I'm working with cryptography on a project and I need a little help on how to work with openssl_encrypt and openssl_decrypt, I just want to know the most basic and correct way to do it. Here is what I got so far:
// 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);
I then store $cypherMethod, $key, and $iv for use when decrypting the $encryptedData. (Let's not elaborate how I store the values, thanks!)
// To decrypt an encrypted string
$decryptedData = openssl_decrypt($encryptedData, $cypherMethod, $key, $options=0, $iv);
First off, is the above example code a correct example of how to use php openssl_encrypt?
Second, is my method to generate the $key and $iv correct and secure? Because I keep on reading, keys should be cryptographically secure.
Lastly, isn't a 32-byte value required for AES-256-CBC? If yes, then why is it that openssl_cipher_iv_length() returns only int(16) as the length? Shouldn't it be int(32)?