Aes.class.php 1.97 KB
<?php
namespace Think\Crypt\Driver;

/**
 * Aes 加密解密类
 */
class Aes
{
    /**
     * 密钥
     */
    private $_encrypt_key = 'JG4FrcGYunxfXiFQ';

    /**
     * 密钥偏移量
     */
    private $_iv = 'JG4FrcGYunxfXiFQ';

    /**
     * 构造函数
     * @param string $encrypt_key 密钥
     * @param string $iv 密钥偏移量
     * @return Aes
     */
    public function __construct($encrypt_key = '', $iv = '')
    {
        if (!empty($encrypt_key)) {
            $this->_encrypt_key = $encrypt_key;
        }

        if (!empty($iv)) {
            $this->_iv = $iv;
        }
    }

    /**
     * 加密字符串
     * @param string $str 字符串
     * @return string
     */
    public function encrypt($str)
    {
        if (empty($str)) {
            return '';
        }

        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $this->_iv);
        mcrypt_generic_init($module, $this->_encrypt_key, $this->_iv);
        // padding
        $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $pad = $block - (strlen($str) % $block);
        $str .= str_repeat(chr($pad), $pad);
        // encrypt
        $encrypted = mcrypt_generic($module, $str);
        mcrypt_generic_deinit($module);
        mcrypt_module_close($module);
        return base64_encode($encrypted);
    }

    /**
     * 解密字符串
     * @param string $str 字符串
     * @return string
     */
    public function decrypt($str)
    {
        if (empty($str)) {
            return '';
        }

        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $this->_iv);
        mcrypt_generic_init($module, $this->_encrypt_key, $this->_iv);
        $encryptedData = base64_decode($str);
        $encryptedData = mdecrypt_generic($module, $encryptedData);

        // 过滤 padding
        $len = strlen($encryptedData);
        $padding = ord($encryptedData[$len - 1]);
        return substr($encryptedData, 0, -$padding);
    }
}