Skip to content

Instantly share code, notes, and snippets.

@ilzrv
Created July 14, 2019 06:09
Show Gist options
  • Save ilzrv/5003fa78c5b8965a3ef09fe4b919563a to your computer and use it in GitHub Desktop.
Save ilzrv/5003fa78c5b8965a3ef09fe4b919563a to your computer and use it in GitHub Desktop.
encrypt & decrypt data
<?php
if (! function_exists('encrypt_data')) {
/**
* Зашифровать значение,
* используя ключ
*
* @param $data
* @param $key
* @param bool $serialize
* @param string $cipher
* @return string
*/
function encrypt_data($data, $key = null, $serialize = true, $cipher = 'aes-256-cbc')
{
$key = $key ?: config('app.key');
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($cipher));
$encrypted = openssl_encrypt($serialize ? serialize($data) : $data, $cipher, $key, 0, $iv);
return $encrypted . ':' . base64_encode($iv);
}
}
if (! function_exists('decrypt_data')) {
/**
* Расшифровать значение,
* используя ключ
*
* @param $data
* @param $key
* @param bool $unserialize
* @param string $cipher
* @return mixed|string
*/
function decrypt_data($data, $key = null, $unserialize = true, $cipher = 'aes-256-cbc')
{
$key = $key ?: config('app.key');
$parts = explode(':', $data);
$decrypted = openssl_decrypt($parts[0], $cipher, $key, 0, base64_decode($parts[1]));
return $unserialize ? unserialize($decrypted) : $decrypted;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment