5.2.1。AES / ECB / PKCS5Padding
<?php class CryptAES {protected $ cipher = MCRYPT_RIJNDAEL_128; 受保护的$ mode = MCRYPT_MODE_ECB; 保护$ pad_method = NULL; 保护$ secret_key =''; 保护$ iv =''; public function set_cipher($ cipher){$ this-> cipher = $ cipher; } public function set_mode($ mode){$ this-> mode = $ mode; } public function set_iv($ iv){$ this-> iv = $ iv; } public function set_key($ key){$ this-> secret_key = $ key; } public function require_pkcs5(){$ this-> pad_method ='pkcs5'; }保护函数pad_or_unpad($ str,$ ext){if(is_null($ this-> pad_method)){return $ str; }其他{$ func_name = __CLASS__。'::'。$ this-> pad_method。'_'。$ ext。'垫'; if(is_callable($ func_name)){$ size = mcrypt_get_block_size($ this-> cipher,$ this-> mode); 返回call_user_func($ func_name,$ str,$ size); }} return $ str; ($ str){return $ this-> pad_or_unpad($ str,''); }保护函数unpad($ str){return $ this-> pad_or_unpad($ str,'un'); }公共函数加密($ str){$ str = $ this-> pad($ str); $ td = mcrypt_module_open($ this-> cipher,'',$ this-> mode,''); 如果(空($ this->)iv)){$ iv = @ mcrypt_create_iv(mcrypt_enc_get_iv_size($ td),MCRYPT_RAND); } else {$ iv = $ this-> iv; } mcrypt_generic_init($ td,$ this-> secret_key,$ iv); $ cyper_text = mcrypt_generic($ td,$ str); // $ rt = bin2hex($ cyper_text); $ rt = base64_encode($ cyper_text); mcrypt_generic_deinit($ TD); mcrypt_module_close($ TD); 返回$ rt; ($ str){$ td = mcrypt_module_open($ this-> cipher,'',$ this-> mode,''); if(empty($ this-> iv)){$ iv = @mcrypt_create_iv(mcrypt_enc_get_iv_size($ td),MCRYPT_RAND); } else {$ iv = $ this-> iv; } mcrypt_generic_init($ td,$ this-> secret_key,$ iv); // $ decrypted_text = mdecrypt_generic($ td,self :: hex2bin($ str)); $ decrypted_text = mdecrypt_generic($ td,base64_decode($ str)); $ rt = $ decrypted_text; mcrypt_generic_deinit($ TD); mcrypt_module_close($ TD); 返回$ this-> unpad($ rt); } public static function hex2bin($ hexdata){$ bindata =''; $ length = strlen($ hexdata); for($ i = 0; $ i <$ length; $ i + = 2){$ bindata。= chr(hexdec(substr($ hexdata,$ i,2))); } return $ bindata; } public static function pkcs5_pad($ text,$ blocksize){$ pad = $ blocksize - (strlen($ text)%$ blocksize); 返回$文本。str_repeat(chr($ pad),$ pad); } public static function pkcs5_unpad($ text){$ pad = ord($ text {strlen($ text) - 1}); 如果($ pad> strlen($ text))返回false; if(strspn($ text,chr($ pad),strlen($ text) - $ pad)!= $ pad)return false; 返回substr($文本,0,-1 * $垫); }} $ aes = new CryptAES(); $ AES-> set_key( 'NGjPs5cgNS497sdx'); $ AES-> require_pkcs5(); $ rt = $ aes-> encrypt('ABC'); echo $ rt。'<BR/>'; echo $ aes-> decrypt($ rt)。'<BR/>';
原文出处:Netkiller 系列 手札
本文作者:陈景峯
转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。