PHP实现加密解密算法

原创
2016-06-21 08:52:51 1046浏览

PHP实现加密解密的算法,如下代码:

  1. class Mcrypt
  2. {
  3. /**
  4. * 解密
  5. *
  6. * @param string $encryptedText 已加密字符串
  7. * @param string $key 密钥
  8. * @return string
  9. */
  10. public static function _decrypt($encryptedText,$key = null)
  11. {
  12. $key = $key === null ? Config::get('secret_key') : $key;
  13. $cryptText = base64_decode($encryptedText);
  14. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  15. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  16. $decryptText = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $key, $cryptText, MCRYPT_MODE_ECB, $iv);
  17. return trim($decryptText);
  18. }
  19. /**
  20. * 加密
  21. *
  22. * @param string $plainText 未加密字符串
  23. * @param string $key 密钥
  24. */
  25. public static function _encrypt($plainText,$key = null)
  26. {
  27. $key = $key === null ? Config::get('secret_key') : $key;
  28. $ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
  29. $iv = mcrypt_create_iv($ivSize, MCRYPT_RAND);
  30. $encryptText = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $key, $plainText, MCRYPT_MODE_ECB, $iv);
  31. return trim(base64_encode($encryptText));
  32. }
  33. }
  34. //调用
  35. class Cookie extends Mcrypt
  36. {
  37. /**
  38. * 删除cookie
  39. *
  40. * @param array $args
  41. * @return boolean
  42. */
  43. public static function del($args)
  44. {
  45. $name = $args['name'];
  46. $domain = isset($args['domain']) ? $args['domain'] : null;
  47. return isset($_COOKIE[$name]) ? setcookie($name, '', time() - 86400, '//m.sbmmt.com/m/', $domain) : true;
  48. }
  49. /**
  50. * 得到指定cookie的值
  51. *
  52. * @param string $name
  53. */
  54. public static function get($name)
  55. {
  56. return isset($_COOKIE[$name]) ? parent::_decrypt($_COOKIE[$name]) : null;
  57. }
  58. /**
  59. * 设置cookie
  60. *
  61. * @param array $args
  62. * @return boolean
  63. */
  64. public static function set($args)
  65. {
  66. $name = $args['name'];
  67. $value= parent::_encrypt($args['value']);
  68. $expire = isset($args['expire']) ? $args['expire'] : null;
  69. $path = isset($args['path']) ? $args['path'] : '//m.sbmmt.com/m/';
  70. $domain = isset($args['domain']) ? $args['domain'] : null;
  71. $secure = isset($args['secure']) ? $args['secure'] : 0;
  72. return setcookie($name, $value, $expire, $path, $domain, $secure);
  73. }
  74. }



声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。