/** * 加密 */
public static function encrypt($encryptStr) { $localIV = '4ID55JgUFcF6KpZd';//$this->iv;偏移量 $encryptKey = '5EfAfL7aUDC4A%vE';//$this->encryptKey;密钥 $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_ECB, $localIV);//打开算法和模式对应的模块 mcrypt_generic_init($module, $encryptKey, $localIV);//初始化加密所需的缓冲区 $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_ECB);//计算加密后的分组大小 $pad = $block - (strlen($encryptStr) % $block); //计算多少字符需要被填充 //chr()返回指定的字符 str_repeat()重复一个字符串 $encryptStr .= str_repeat(chr($pad), $pad); //填充后,字符长度必须等于加密算法的分组大小或它的整数倍 $encrypted = mcrypt_generic($module, $encryptStr);//进行加密数据 mcrypt_generic_deinit($module);//对加密模块进行清理工作 mcrypt_module_close($module);//关闭加密模块 return base64_encode($encrypted);//使用 MIME base64 对数据进行编码 }
/** * 解密 */ static function decrypt($data) { $dec_key = '6EsUfL4aUfC9A%vE';//随机生成16位由大小写字符和数字组成的字符串 $data = base64_decode($data);//base64 $dec_iv = '3ID75JbUFcF7KpZe'; $method = MCRYPT_RIJNDAEL_128; $mode = MCRYPT_MODE_ECB; $td = mcrypt_module_open($method, '', $mode, ''); mcrypt_generic_init($td , $dec_key , $dec_iv); $decrypt = mdecrypt_generic($td, $data);//解密数据 // $decrypt = rtrim($decrypt , ['\0','+']); mcrypt_generic_deinit($td); mcrypt_module_close($td); //去除填充 $pad = ord($decrypt[($len = strlen($decrypt))-1]);//ord()返回字符的ASCII码 //优化 $beforePad = strlen($decrypt) - $pad; $decrypt = substr($decrypt, $beforePad) == str_repeat(substr($decrypt, -1), $pad) ? substr($decrypt, 0, $len - $pad) : $decrypt; return $decrypt; }