Skip to content

Instantly share code, notes, and snippets.

@BERRAMOU
Created April 18, 2019 10:49
Show Gist options
  • Save BERRAMOU/6126effb844d6b49ec2748e076d4c6f9 to your computer and use it in GitHub Desktop.
Save BERRAMOU/6126effb844d6b49ec2748e076d4c6f9 to your computer and use it in GitHub Desktop.
Drupal 7 encrypt decrypt string example
<?
/**
* Function to encrypt and decrypt a string.
* @param $string
* @param string $action
*
* @return bool|string
*/
function _custom_encrypt_decrypt($string, $action = 'encrypt') {
$secret_key = 'k;Yj>+kZ@CHBJQDs*G=2!uRXE+4;)H(M';
$secret_iv = 'F5a:~+EQAj#:>zazNWN6GP3JEWX75h-@';
$output = FALSE;
$encrypt_method = "AES-256-CBC";
$key = hash('sha256', $secret_key);
$iv = substr(hash('sha256', $secret_iv), 0, 4);
if ($action == 'encrypt') {
$output = base64_encode(openssl_encrypt($string, $encrypt_method, $key, 0, $iv));
}
elseif ($action == 'decrypt') {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment