<?php
$textToEncrypt = "Secret Text to Encrypt";
$encryptionMethod = 'aes-256-cbc';
$secretHash = "315a5504d921f8327f73a356d2bbcbf1"; // <---- you have to use some persistent.
$iv_size = openssl_cipher_iv_length($encryptionMethod );
$iv = openssl_random_pseudo_bytes($iv_size);
//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash, 0, $iv);
//Concatenate iv with data
$encryptedMessageWithIv = bin2hex($iv) . $encryptedMessage;
//To Decrypt
$iv_size = openssl_cipher_iv_length($encryptionMethod );
$iv = hex2bin(substr($encryptedMessageWithIv, 0, $iv_size*2));
$decryptedMessage = openssl_decrypt(substr($encryptedMessageWithIv, $iv_size*2), $encryptionMethod, $secretHash, 0, $iv);
echo "Encrypted: $encryptedMessageWithIv <br>Decrypted: $decryptedMessage";
preferences:
39.95 ms | 402 KiB | 5 Q