Add a concise PHP reversible encryption function

Source: Internet
Author: User

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

The encryption process is as follows:

// Encrypt the data and write it to the cookie $ cookie_data = $ this-> encrypt ("bkjia", $ data); $ cookie = array ('name' => '$ data ', 'value' => $ cookie_data, 'expire '=> $ user_expire, 'domain' => '', 'path' => '/', 'prefix' => ''); $ this-> input-> set_cookie ($ cookie); // encrypt the public function encrypt ($ key, $ plain_text) {$ plain_text = trim ($ plain_text); $ iv = substr (md5 ($ key), 0, encrypt (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 it when using it:

If (isset ($ _ COOKIE ['data']) {// use a cookie to assign a value to the session $ _ SESSION ['data'] = decrypt ("bkjia ", $ _ COOKIE ['data']);} function decrypt ($ key, $ c_t) {$ c_t = trim (chop (base64_decode ($ c_t ))); $ iv = substr (md5 ($ key), 0, encrypt (MCRYPT_CAST_256, encrypt); $ p_t = mcrypt_cfb (MCRYPT_CAST_256, $ key, $ c_t, MCRYPT_DECRYPT, $ iv ); return trim (chop ($ p_t ));}

Here we will record the use of this reversible encryption function.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.