PHP reversible encryption/decryption function Instance code

Source: Internet
Author: User
For most password encryption, we can use MD5, SHA1 and other methods.

Can effectively prevent data breaches, but these methods apply only to data encryption that does not need to be restored.

For information that needs to be restored, a reversible cryptographic decryption algorithm is required.

Many of the project's membership system, are required to remember the login function, in the use of cookies to realize the function is, because the customer information to be stored directly to the cookies, if directly written to the cookies will be a security risk, so by reversible encryption and then save to the cookie is relatively safe

Function source Code

function Encrypt ($data, $key) {$prep _code = serialize ($data); $block = Mcrypt_get_block_size (' des ', ' ECB '); if ($pad = $ Block-(strlen ($prep _code)% $block) < $block) {$prep _code. = Str_repeat (Chr ($pad), $pad);} $encrypt = Mcrypt_encry PT (Mcrypt_des, $key, $prep _code, MCRYPT_MODE_ECB); Return Base64_encode ($encrypt); } function Decrypt ($STR, $key) {$str = Base64_decode ($str); $str = Mcrypt_decrypt (Mcrypt_des, $key, $str, MCRYPT_MODE_ECB ); $block = Mcrypt_get_block_size (' des ', ' ECB '); $pad = Ord ($str [($len = strlen ($STR))-1]); if ($pad && $pad < $block && Preg_match ('/'. Chr ($pad). ' {'. $pad. '}$/', $str)) {$str = substr ($str, 0, strlen ($str)-$pad);} return Unserialize ($STR); }

Calling functions

 $key = ' okyo.cn '; $data = array (' id ' = ' = ', ' username ' = ' customer ', ' Passwo Rd ' = ' e10adc3949ba59abbe56e057f20f883e '); $snarr = serialize ($data); $en = Encrypt ($data, $key); $de = Decrypt ($en, $key); echo "Crypto prototype:"; Print_r ($data); echo "key: $key encryption Result: $en decryption result:"; Print_r ($de); 
Related Article

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.