Я использую следующий код, где мой секрет хранится в файле parameters.yml, поэтому он не будет виден, если вы отправите его в Git.
/**
* SecurityHelper.
*
* @author Kengy Van Hijfte <development@kengy.be>
*/
class SecurityHelper
{
/** @var string $secret */
private $secret;
public function __construct($secret)
{
$this->secret = $secret;
}
/**
* @param $text
* @return string
*/
public function encrypt($text)
{
if (null == $text)
return null;
// Generate an initialization vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
// Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
$encrypted = openssl_encrypt($text, 'aes-256-cbc', $this->secret, 0, $iv);
// The $iv is just as important as the key for decrypting, so save it with our encrypted data using a unique separator (::)
return base64_encode($encrypted . '::' . $iv);
}
/**
* @param $text
* @return string
*/
public function decrypt($text)
{
if (null == $text)
return null;
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
list($encrypted_data, $iv) = explode('::', base64_decode($text), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $this->secret, 0, $iv);
}
}