php aes cbc

WBOY
Release: 2016-06-23 13:35:59
Original
1165 people have browsed it

class aes_mcrypt {    private $hex_iv = '00000000000000000000000000000000'; # converted JAVA byte code in to HEX and placed it here    function __construct($key) {        $this->key = hash('sha256',$key, true);    }    function encrypt($str) {        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');        mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));        //$block = mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC);        $block = mcrypt_enc_get_block_size($td);        $str = $this->addpadding($str,$block);        $encrypted = mcrypt_generic($td, $str);        mcrypt_generic_deinit($td);        mcrypt_module_close($td);        return base64_encode($encrypted);    }    function decrypt($code) {        $td = mcrypt_module_open(MCRYPT_RIJNDAEL_128, '', MCRYPT_MODE_CBC, '');        mcrypt_generic_init($td, $this->key, $this->hexToStr($this->hex_iv));        $str = mdecrypt_generic($td, base64_decode($code));        mcrypt_generic_deinit($td);        mcrypt_module_close($td);        return $this->strippadding($str);    }    /*      For PKCS7 padding     */    private function addpadding($string, $blocksize = 16) {        $len = strlen($string);        $pad = $blocksize - ($len % $blocksize);        $string .= str_repeat(chr($pad), $pad);        return $string;    }    private function strippadding($string) {        $slast = ord(substr($string, -1));        $slastc = chr($slast);        $pcheck = substr($string, -$slast);        if (preg_match("/$slastc{" . $slast . "}/", $string)) {            $string = substr($string, 0, strlen($string) - $slast);            return $string;        } else {            return false;        }    }    public function hexToStr($hex)    {        $string='';        for ($i=0; $i < strlen($hex)-1; $i+=2)        {            $string .= chr(hexdec($hex[$i].$hex[$i+1]));        }        return $string;    }}
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!