PHP 实现AES/CBC/PKCS5Padding加解密(对称加密)

/**
 * Class Aes
 */
class Aes {
    private $iv = '';//密钥偏移量IV,可自定义
    private $encryptKey = '';//AESkey,可自定义

    public function set_key($key){
        $this->encryptKey = $key;
    }

    public function set_iv($iv){
        $this->iv = $iv;
    }

    //加密
    public function encrypt($encryptStr) {
        $localIV = $this->iv;
        $encryptKey = $this->encryptKey;

        //Open module
        $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV);

        //print "module = $module 
" ; mcrypt_generic_init($module, $encryptKey, $localIV); //Padding $block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC); $pad = $block - (strlen($encryptStr) % $block); //Compute how many characters need to pad $encryptStr .= str_repeat(chr($pad), $pad); // After pad, the str length must be equal to block or its integer multiples //encrypt $encrypted = mcrypt_generic($module, $encryptStr); //Close mcrypt_generic_deinit($module); mcrypt_module_close($module); return urlsafe_b64encode($encrypted); } //解密 public function decrypt($encryptStr) { $localIV = $this->iv; $encryptKey = $this->encryptKey; //Open module $module = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, $localIV); //print "module = $module
" ; mcrypt_generic_init($module, $encryptKey, $localIV); $encryptedData = urlsafe_b64decode($encryptStr); $encryptedData = mdecrypt_generic($module, $encryptedData); return $encryptedData; } }

其中urlsafe_b64encode()和urlsafe_b64decode()函数可以在我的其他博客里面查找!!

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