当前位置: 首页 > 后端技术 > PHP

PHPAES加密解密(ECB模式-sha1prng算法-PKCS5Padding与PKCS7Padding补全)

时间:2023-03-29 21:16:54 PHP

php7+版本/***[AesSecurityaes加密,支持PHP7+]*算法模式:ECB*密钥长度:128*补码方式:PKCS7Padding*解密字符串编码方式:base64/hexadecimal*/classAes{/***[encryptaes加密]*@param[type]$input[待加密数据]*@param[type]$key[加密密钥]*@return[type][加密数据]*/publicstaticfunctionencrypt($input,$键){$key=self::_sha1prng($key);$iv='';$data=openssl_encrypt($input,'AES-128-ECB',$key,OPENSSL_RAW_DATA,$iv);$data=base64_encode($data);返回$数据;}/***[decryptaes解密]*@param[type]$sStr[待解密数据]*@param[type]$sKey[加密密钥]*@return[type][解密数据]*/publicstatic函数解密($sStr,$sKey){$sKey=self::_sha1prng($sKey);$iv='';$decrypted=openssl_decrypt(base64_decode($sStr),'AES-128-ECB',$sKey,OPENSSL_RAW_DATA,$iv);返回$解密;}/***SHA1PRNG算法*@param[type]$key[description]*@return[type][description]*/privatestaticfunction_sha1prng($key){returnsubstr(openssl_digest(openssl_digest($key,'sha1',真),'sha1',真),0,16);}}php5.6version/***[Aesaes加密,支持PHP5+]*算法模式:ECB*密钥长度:128*补码方式:PKCS5Padding/PKCS7Padding*解密字符串编码方式:base64/hexadecimal*/classAes{publicstaticfunctionencrypt($plain,$key){if(trim($key)==''){返回假;}$plain=strval($plain);$block_size=mcrypt_get_block_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB);$padded_data=self::_pkcs5_pad($plain,$block_size);$iv_size=mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB);$iv=mcrypt_create_iv($iv_size,MCRYPT_RAND);$encrypted=mcrypt_encrypt(MCRYPT_RIJNDAEL_128,self::_sha1prng($key),$padded_data,MCRYPT_MODE_ECB,$iv);返回base64_encode($encrypted);}publicstaticfunctiondecrypt($cipher,$key){if(!is_string($cipher)||trim($key)==''){返回假;}if($decoded=base64_decode($cipher)){$block_size=mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128,MCRYPT_MODE_ECB);$iv=mcrypt_create_iv($block_size,MCRYPT_RAND);$decrypted=mcrypt_decrypt(MCRYPT_RIJNDAEL_128,self::_sha1prng($key),$decoded,MCRYPT_MODE_ECB,$iv);返回self::_pkcs5_unpad($decrypted);}返回假;}privatestaticfunction_sha1prng($key){returnsubstr(openssl_digest(openssl_digest($key,'sha1',true),'sha1',true),0,16);}privatestaticfunction_pkcs5_pad($text,$block_size){$pad=$block_size-(strlen($text)%$block_size);返回$text。str_repeat(chr($pad),$垫);}privatestaticfunction_pkcs5_unpad($text){$end=substr($text,-1);$last=ord($end);$len=strlen($text)-$last;如果(substr($text,$len)==str_repeat($end,$last)){returnsubstr($text,0,$len);}返回假;}privatestaticfunction_pkcs7_pad($string,$blocksize=32){$len=strlen($string);$pad=$blocksize-($len%$blocksize);$string.=str_repeat(chr($pad),$pad);返回$字符串;}privatestaticfunction_pkcs7_unpad($string){$pad=ord($string{strlen($string)-1});如果($pad>strlen($string)){返回false;}if(strspn($string,chr($pad),strlen($string)-$pad)!=$pad){returnfalse;}returnsubstr($string,0,-1*$pad);}}代码中的相关算法算法模式:ECB密钥长度:128补码方式:PKCS5Padding解密字符串编码方式:base64/hexadecimalECB模式不需要设置iv工作忙,时间有限,再讨论下次吧~注:php5.6以下版本未测试,请尝试使用5.6.x及以上版本