A simple PHP reversible encryption function (share)_PHP tutorial

WBOY
Release: 2016-07-21 15:08:37
Original
879 people have browsed it

Many times we need to encrypt and decrypt data. For example, some data needs to be saved in cookies, but the data cannot be easily obtained by users. In this case, we need to encrypt the data and save it in cookies until we need to use it. Decrypt it later.

The encryption process is as follows:

Copy the code The code is as follows:

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

$cookie = array(
'name' = > '$data',
'value' => $cookie_data,
'expire' => $user_expire,
'domain' => '',
'path' = > '/',
'prefix' => ''
);
$this->input->set_cookie($cookie);

/ / 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']) )
{
//Use cookie to assign value to session
$_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.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327440.htmlTechArticleMany times we need to encrypt and decrypt data. For example, some data needs to be saved in cookies, but cannot be used by users. It is easy to get this data, then we need to encrypt these data...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template