A concise PHP reversible encryption function

WBOY
Release: 2016-07-25 08:43:19
Original
947 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. At this time, we need to encrypt the data and save it in cookies until we need to use them. Decrypt again.

  1. // Encrypt data and write it to cookie
  2. $cookie_data = $this -> encrypt("nowamagic", $data);
  3. $cookie = array(
  4. 'name' => '$data ',
  5. 'value' => $cookie_data,
  6. 'expire' => $user_expire,
  7. 'domain' => '',
  8. 'path' => '/',
  9. 'prefix' => ''
  10. );
  11. $this->input->set_cookie($cookie);
  12. // Encryption
  13. public function encrypt($key, $plain_text) {
  14. $plain_text = trim($plain_text);
  15. $ iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  16. $c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);
  17. return trim(chop(base64_encode($c_t )));
  18. }
  19. Decrypt when using:
  20. if( isset($_COOKIE['data']) )
  21. {
  22. //Use cookie to assign value to session
  23. $_SESSION['data'] = decrypt(" nowamagic", $_COOKIE['data']);
  24. }
  25. function decrypt($key, $c_t) {
  26. $c_t = trim(chop(base64_decode($c_t)));
  27. $iv = substr(md5( $key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
  28. $p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);
  29. return trim(chop($p_t));
  30. }
Copy code

The use of this reversible encryption function is recorded here.

PHP


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!