php mcrypt 加密解密类

<?php
/**
  * @brief      AES加密解密类
  */
class Aes {
        //加密密钥
        private $key = 'secret';
        //加密模式
        private $mode = MCRYPT_MODE_CBC;
        //加密随机
        private $rand = MCRYPT_DEV_URANDOM;
        //加密计算方法
        private $cipher = MCRYPT_RIJNDAEL_256;

        /** 
          * @brief      设置加密密钥
          * @param string $key  加密密钥
          * @return     void
          */
        public function setKey($key) {
                $this->key = $key;
        }   

        /** 
          * @brief      设置加密计算方法
          * @param string $cipher       计算方法
          * @return     void
          */
        public function setCipher($cipher) {
                $this->cipher = $cipher;
        }   

        /** 
          * @brief      设置加密模式
          * @param string $mode 加密模式
          * @return     void
          */
        public function setMode($mode) {
                $this->mode = $mode;
        }   

        /** 
          * @brief      字符串加密
          * @param string $data 加密字符串
          * @return string      加密后的字符串
          */
        public function encrypt($data) {
                $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
                $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), $this->rand);
                mcrypt_generic_init($td, $this->key, $iv);
                $encrypt = mcrypt_generic($td, $data);
                mcrypt_generic_deinit($td);
                $encrypt = mcrypt_generic($td, $data);
                mcrypt_generic_deinit($td);
                mcrypt_module_close($td);
                return $iv . $encrypt;
        }

        /**
          * @brief      字符串解密
          * @param string $data 解密的字符串
          * @return string      解密后的字符串
          */
        public function decrypt($data) {
                $td = mcrypt_module_open($this->cipher, '', $this->mode, '');
                $size = mcrypt_enc_get_iv_size($td);
                $iv = mb_substr($data, 0, $size, 'latin1');
                mcrypt_generic_init($td, $this->key, $iv);
                $data = mb_substr($data, $size, mb_strlen($data, 'latin1'), 'latin1');
                $decrypt = mdecrypt_generic($td, $data);
                mcrypt_generic_deinit($td);
                mcrypt_module_close($td);
                return trim($decrypt);
        }
}
?>

你可能感兴趣的:(PHP,加密解密,mcrypt)