English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
php Implement a string encryption and decryption function
Function Code as follows:
/********************************************************************* Function Name: encrypt Function Purpose: Encrypt or decrypt strings Usage Method: Encryption :encrypt('str','E','nowamagic'); Decryption :encrypt('The encrypted string','D','nowamagic'); Parameter Description: $string : The string to be encrypted or decrypted $operation: Determines whether it is encryption or decryption: E: Encryption D: Decryption $key :The encryption key (cipher key); http://www.cnblogs.com/roucheng/ *********************************************************************/ function encrypt($string,$operation,$key='') { $key=md5($key); $key_length=strlen($key); $string=$operation=='D'?base64_decode($string):substr(md5($string.$key),0,8).$string; $string_length=strlen($string); $rndkey=$box=array(); $result=''; for($i=0;$i<=255;$i++) { $rndkey[$i]=ord($key[$i%$key_length]); $box[$i]=$i; } for($j=$i=0;$i<256;$i++) { $j=($j+$box[$i]+$rndkey[$i])%256; $tmp=$box[$i]; $box[$i]=$box[$j]; $box[$j]=$tmp; } for($a=$j=$i=0;$i<++) { $a=($a+1)%256; $j=($j+$box[$a])%256; $tmp=$box[$a]; $box[$a]=$box[$j]; $box[$j]=$tmp; $result.=chr(ord($string[$i])^($box[($box[$a+$box[$j])%256]); } { if(substr($result,0,85(substr($result,8).$key),0,8 { return substr($result,8); } else { return''; } } else { return str_replace('=','',base64_encode($result)); } }
Example Usage:
$id = 132; $token = encrypt($id, 'E', 'a'); echo 'Encryption:'.encrypt($id, 'E', 'a'); /> echo 'Decryption:'.encrypt($token, 'D', 'a');
Running Result:
Encryption: AYCnIibFlg3ViRs
Decryption:132
Thank you for reading, I hope it can help you. Thank you for your support of this site!