Aes.Class.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace Mall\Framework\Core;
  3. class Aes
  4. {
  5. private $_iv = "0102030405060708";
  6. private $_encryptKey;
  7. private static $_instance;
  8. public function __construct ($encryptKey = '')
  9. {
  10. $this->_encryptKey = $encryptKey ?: defined('SITE_SECRET') ?: 'h7WPzPi87}MC7AxM6Jz)L?9%NXy*jB';
  11. }
  12. public static function getInstance($encryptKey = [])
  13. {
  14. if (!self::$_instance instanceof self) {
  15. self::$_instance = new self($encryptKey);
  16. }
  17. return self::$_instance;
  18. }
  19. public function encrypt($encryptStr)
  20. {
  21. $localIV = $this->_iv;
  22. $encryptKey = $this->_encryptKey;
  23. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  24. mcrypt_generic_init($module, $encryptKey, $localIV);
  25. $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
  26. $pad = $block - (strlen($encryptStr) % $block);
  27. $encryptStr .= str_repeat(chr($pad), $pad);
  28. $encrypted = mcrypt_generic($module, $encryptStr);
  29. mcrypt_generic_deinit($module);
  30. mcrypt_module_close($module);
  31. return base64_encode($encrypted);
  32. }
  33. public function decrypt($encryptStr)
  34. {
  35. $localIV = $this->_iv;
  36. $encryptKey = $this->_encryptKey;
  37. $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);
  38. mcrypt_generic_init($module, $encryptKey, $localIV);
  39. $encryptedData = base64_decode($encryptStr);
  40. $encryptedData = mdecrypt_generic($module, $encryptedData);
  41. return $encryptedData;
  42. }
  43. }