You can use openssl_random_pseudo_bytes (len, & crypto_stron) .
The first parameter is the length you want in bytes. If you use this for use in one of the public ssl methods, you can use the openssl_cipher_iv_length function (method) to get the correct length for the method used.
The second parameter & crypto_strong allows you to pass a logical variable that will be set to true or false depending on whether the algorithm used is cryptographically protected. Then you can check this variable and process it correctly if the variable returns false. This should never happen, but if it does, you probably want to know.
Here is an example of proper use:
$method = 'aes-256-cbc'; $ivlen = openssl_cipher_iv_length($method); $isCryptoStrong = false; // Will be set to true by the function if the algorithm used was cryptographically secure $iv = openssl_random_pseudo_bytes($ivlen, $isCryptoStrong); if(!$isCryptoStrong) throw new Exception("Non-cryptographically strong algorithm used for iv generation. This IV is not safe to use.");
For more information see
source share