2個比較經(jīng)典的PHP加密解密函數(shù)分享_PHP
Jun 01, 2016 am 11:51 AM項目中有時我們需要使用PHP將特定的信息進行加密,也就是通過加密算法生成一個加密字符串,這個加密后的字符串可以通過解密算法進行解密,便于程序?qū)饷芎蟮男畔⑦M行處理。
最常見的應(yīng)用在用戶登錄以及一些API數(shù)據(jù)交換的場景。
筆者收錄了一些比較經(jīng)典的PHP加密解密函數(shù)代碼,分享給大家。加密解密原理一般都是通過一定的加密解密算法,將密鑰加入到算法中,最終得到加密解密結(jié)果。
1、非常給力的authcode加密函數(shù),Discuz!經(jīng)典代碼(帶詳解):
復(fù)制代碼 代碼如下:
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {??
??? // 動態(tài)密匙長度,相同的明文會生成不同密文就是依靠動態(tài)密匙??
??? $ckey_length = 4;??
??????
??? // 密匙??
??? $key = md5($key ? $key : $GLOBALS['discuz_auth_key']);??
??????
??? // 密匙a會參與加解密??
??? $keya = md5(substr($key, 0, 16));??
??? // 密匙b會用來做數(shù)據(jù)完整性驗證??
??? $keyb = md5(substr($key, 16, 16));??
??? // 密匙c用于變化生成的密文??
??? $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length):
substr(md5(microtime()), -$ckey_length)) : '';??
??? // 參與運算的密匙??
??? $cryptkey = $keya.md5($keya.$keyc);??
??? $key_length = strlen($cryptkey);??
??? // 明文,前10位用來保存時間戳,解密時驗證數(shù)據(jù)有效性,10到26位用來保存$keyb(密匙b),
//解密時會通過這個密匙驗證數(shù)據(jù)完整性??
??? // 如果是解碼的話,會從第$ckey_length位開始,因為密文前$ckey_length位保存 動態(tài)密匙,以保證解密正確??
??? $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) :?
sprintf('%010d', $expiry ? $expiry + time() : 0).substr(md5($string.$keyb), 0, 16).$string;??
??? $string_length = strlen($string);??
??? $result = '';??
??? $box = range(0, 255);??
??? $rndkey = array();??
??? // 產(chǎn)生密匙簿??
??? for($i = 0; $i
??????? $rndkey[$i] = ord($cryptkey[$i % $key_length]);??
??? }??
??? // 用固定的算法,打亂密匙簿,增加隨機性,好像很復(fù)雜,實際上對并不會增加密文的強度??
??? for($j = $i = 0; $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;??
??????? // 從密匙簿得出密匙進行異或,再轉(zhuǎn)成字符??
??????? $result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));??
??? }??
??? if($operation == 'DECODE') {?
??????? // 驗證數(shù)據(jù)有效性,請看未加密明文的格式??
??????? if((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0) &&?
substr($result, 10, 16) == substr(md5(substr($result, 26).$keyb), 0, 16)) {??
??????????? return substr($result, 26);??
??????? } else {??
??????????? return '';??
??????? }??
??? } else {??
??????? // 把動態(tài)密匙保存在密文里,這也是為什么同樣的明文,生產(chǎn)不同密文后能解密的原因??
??????? // 因為加密后的密文可能是一些特殊字符,復(fù)制過程可能會丟失,所以用base64編碼??
??????? return $keyc.str_replace('=', '', base64_encode($result));??
??? }??
}
函數(shù)authcode($string, $operation, $key, $expiry)中的$string:字符串,明文或密文;$operation:DECODE表示解密,其它表示加密;$key:密匙;$expiry:密文有效期。
用法:
復(fù)制代碼 代碼如下:
$str = 'abcdef';
$key = 'www.helloweba.com';
echo authcode($str,'ENCODE',$key,0); //加密
$str = '56f4yER1DI2WTzWMqsfPpS9hwyoJnFP2MpC8SOhRrxO7BOk';
echo authcode($str,'DECODE',$key,0); //解密
2、加解密函數(shù)encrypt():
復(fù)制代碼 代碼如下: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
?????????? $rndkey[$i]=ord($key[$i%$key_length]);
??????? $box[$i]=$i;
??? }
??? for($j=$i=0;$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($operation=='D'){
??????? if(substr($result,0,8)==substr(md5(substr($result,8).$key),0,8)){
??????????? return substr($result,8);
??????? }else{
??????????? return'';
??????? }
??? }else{
??????? return str_replace('=','',base64_encode($result));
??? }
}
函數(shù)encrypt($string,$operation,$key)中$string:需要加密解密的字符串;$operation:判斷是加密還是解密,E表示加密,D表示解密;$key:密匙。
用法:
復(fù)制代碼 代碼如下:
$str = 'abc';
$key = 'www.helloweba.com';
$token = encrypt($str, 'E', $key);
echo '加密:'.encrypt($str, 'E', $key);
echo '解密:'.encrypt($str, 'D', $key);

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

TosecurelyhandleauthenticationandauthorizationinPHP,followthesesteps:1.Alwayshashpasswordswithpassword_hash()andverifyusingpassword_verify(),usepreparedstatementstopreventSQLinjection,andstoreuserdatain$_SESSIONafterlogin.2.Implementrole-basedaccessc

To safely handle file uploads in PHP, the core is to verify file types, rename files, and restrict permissions. 1. Use finfo_file() to check the real MIME type, and only specific types such as image/jpeg are allowed; 2. Use uniqid() to generate random file names and store them in non-Web root directory; 3. Limit file size through php.ini and HTML forms, and set directory permissions to 0755; 4. Use ClamAV to scan malware to enhance security. These steps effectively prevent security vulnerabilities and ensure that the file upload process is safe and reliable.

In PHP, the main difference between == and == is the strictness of type checking. ==Type conversion will be performed before comparison, for example, 5=="5" returns true, and ===Request that the value and type are the same before true will be returned, for example, 5==="5" returns false. In usage scenarios, === is more secure and should be used first, and == is only used when type conversion is required.

The methods of using basic mathematical operations in PHP are as follows: 1. Addition signs support integers and floating-point numbers, and can also be used for variables. String numbers will be automatically converted but not recommended to dependencies; 2. Subtraction signs use - signs, variables are the same, and type conversion is also applicable; 3. Multiplication signs use * signs, which are suitable for numbers and similar strings; 4. Division uses / signs, which need to avoid dividing by zero, and note that the result may be floating-point numbers; 5. Taking the modulus signs can be used to judge odd and even numbers, and when processing negative numbers, the remainder signs are consistent with the dividend. The key to using these operators correctly is to ensure that the data types are clear and the boundary situation is handled well.

Yes, PHP can interact with NoSQL databases like MongoDB and Redis through specific extensions or libraries. First, use the MongoDBPHP driver (installed through PECL or Composer) to create client instances and operate databases and collections, supporting insertion, query, aggregation and other operations; second, use the Predis library or phpredis extension to connect to Redis, perform key-value settings and acquisitions, and recommend phpredis for high-performance scenarios, while Predis is convenient for rapid deployment; both are suitable for production environments and are well-documented.

TostaycurrentwithPHPdevelopmentsandbestpractices,followkeynewssourceslikePHP.netandPHPWeekly,engagewithcommunitiesonforumsandconferences,keeptoolingupdatedandgraduallyadoptnewfeatures,andreadorcontributetoopensourceprojects.First,followreliablesource

PHPbecamepopularforwebdevelopmentduetoitseaseoflearning,seamlessintegrationwithHTML,widespreadhostingsupport,andalargeecosystemincludingframeworkslikeLaravelandCMSplatformslikeWordPress.Itexcelsinhandlingformsubmissions,managingusersessions,interacti

TosettherighttimezoneinPHP,usedate_default_timezone_set()functionatthestartofyourscriptwithavalididentifiersuchas'America/New_York'.1.Usedate_default_timezone_set()beforeanydate/timefunctions.2.Alternatively,configurethephp.inifilebysettingdate.timez
