A concise PHP reversible encryption function of share

  • 2020-06-07 04:05:11
  • OfStack

In many cases, we need to encrypt and decrypt the data. For example, some data need to be saved in cookie, but cannot be easily obtained by the user. In this case, we need to encrypt the data and save it in cookie, and then decrypt it when we need to use them.

The encryption process is as follows:

//  Encrypt the data and write cookie In the 
$cookie_data = $this -> encrypt("nowamagic", $data);

$cookie = array(
    'name'   => '$data',
    'value'  => $cookie_data,
    'expire' => $user_expire,
    'domain' => '',
    'path'   => '/',
    'prefix' => ''

//  encryption 
public function encrypt($key, $plain_text) {  
    $plain_text = trim($plain_text);  
    $iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));  
    $c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);  
    return trim(chop(base64_encode($c_t)));  
 Decrypt when used: 
if( isset($_COOKIE['data']) )
    // with cookie to session The assignment 
    $_SESSION['data'] = decrypt("nowamagic", $_COOKIE['data']);

function decrypt($key, $c_t) {  
    $c_t = trim(chop(base64_decode($c_t)));  
    $iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));  
    $p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);  
    return trim(chop($p_t));  

The use of this reversible encryption function is recorded here.

Related articles: