PHP mcrypt 实现对称加密(AES)算法


class Security {
    public static function encrypt($input, $key,$ivstr) {
        $size = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);
        $input = Security::pkcs5_pad($input, $size);
        //echo $input."\n";
        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');
        //$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
        mcrypt_generic_init($td, $key,$ivstr);
        $data = mcrypt_generic($td, $input);
        mcrypt_generic_deinit($td);
        mcrypt_module_close($td);
        //$data = base64_encode($data);
        $data = self::encodeBytes($data);
        return $data;
    }
    public static function encodeBytes($bytes){
        $strBuf = array();
        for ($i = 0,$n = strlen($bytes); $i < $n; $i++) {
            $strBuf[] = chr((ord($bytes[$i]) >> 4 & 0xF) + 97);
            $strBuf[] = chr((ord($bytes[$i]) & 0xF) + 97);
        }
        return implode("", $strBuf);
    }
    public static function decodeBytes($str){
        $bytes = array();;
        for ($i = 0,$n = strlen($str); $i < $n; $i += 2) {
            $c = $str[$i];
            $bytes[$i / 2] = (ord($c) - 97) << 4;
            $c = $str[$i + 1];
            $bytes[$i / 2] += (ord($c) - 97);
            $bytes[$i / 2] = chr($bytes[$i / 2]);
        }
        return implode("", $bytes);
    }
    private static function pkcs5_pad ($text, $blocksize) {
        $pad = $blocksize - (strlen($text) % $blocksize);
        return $text . str_repeat(chr($pad), $pad);
    }
    public static function decrypt($sStr, $sKey,$ivstr) {
        $decrypted= mcrypt_decrypt(
            MCRYPT_RIJNDAEL_128,
            $sKey,
            //base64_decode($sStr),
            self::decodeBytes($sStr),
            MCRYPT_MODE_CBC,
            $ivstr
        );
        $dec_s = strlen($decrypted);
        $padding = ord($decrypted[$dec_s-1]);
        $decrypted = substr($decrypted, 0, -$padding);
        return $decrypted;
    }   
}

$key = "6NnWFvZfe0C_oshu";
$ivstr = "e9ppgxf64kKbDD6k";
$value = Security::encrypt("hello world" , $key ,$ivstr);
echo $value;
echo PHP_EOL;
echo Security::decrypt($value, $key ,$ivstr);
echo PHP_EOL;