數(shù)據(jù)加密在我們生活中的地位已經(jīng)越來(lái)越重要了,尤其是考慮到在網(wǎng)絡(luò)上發(fā)生的大量交易和傳輸?shù)拇罅繑?shù)據(jù)。如果對(duì)于采用安全措施有興趣的話(huà),也一定會(huì)有興趣了解PHP提供的一系列安全功能。在本篇文章中,我們將介紹這些功能,提供一些基本的用法,以便你能夠?yàn)樽约旱膽?yīng)用軟件中增加安全功能。 預(yù)備知識(shí) ??? 在詳細(xì)介紹PHP的安全功能之前,我們需要花點(diǎn)時(shí)間來(lái)向沒(méi)有接觸過(guò)這方面內(nèi)容的讀者介紹一些有關(guān)密碼學(xué)的基本知識(shí),如果對(duì)密碼學(xué)的基本概念已經(jīng)非常熟悉,就可以跳過(guò)去這一部分。 ??? 密碼學(xué)可以通俗地被描述為對(duì)加/解密的研究和實(shí)驗(yàn),加密是將易懂的資料轉(zhuǎn)換為不易懂資料的過(guò)程,解密則是將不易懂的資料轉(zhuǎn)換為原來(lái)易懂資料的過(guò)程。不易懂的資料被稱(chēng)作密碼,易懂的資料被稱(chēng)作明碼。 ??? 數(shù)據(jù)的加/解密都需要一定的算法,這些算法可以非常地簡(jiǎn)單,如著名的凱撒碼,但當(dāng)前的加密算法要相對(duì)復(fù)雜得多,其中一些利用現(xiàn)有的方法甚至是無(wú)法破譯的。 PHP的加密功能 ??? 只要有一點(diǎn)使用非Windows平臺(tái)經(jīng)驗(yàn)的人可能對(duì)crypt()也相當(dāng)熟悉,這一函數(shù)完成被稱(chēng)作單向加密的功能,它可以加密一些明碼,但不能夠?qū)⒚艽a轉(zhuǎn)換為原來(lái)的明碼。盡管從表面上來(lái)看這似乎是一個(gè)沒(méi)有什么用處的功能,但它的確被廣泛用來(lái)保證系統(tǒng)密碼的完整性。因?yàn)?,單向加密的口令一旦落入第三方人的手里,由于不能被還原為明文,因此也沒(méi)有什么大用處。在驗(yàn)證用戶(hù)輸入的口令時(shí),用戶(hù)的輸入采用的也是單向算法,如果輸入與存儲(chǔ)的經(jīng)加密后的口令相匹配,則輸入的口信一定是正確的。 ??? PHP同樣提供了使用其crypt()函數(shù)完成單向加密功能的可能性。我將在這里簡(jiǎn)要地介紹該函數(shù): string crypt (string input_string [, string salt]) ??? 其中的input_string參數(shù)是需要加密的字符串,第二個(gè)可選的salt是一個(gè)位字串,它能夠影響加密的暗碼,進(jìn)一步地排除被稱(chēng)作預(yù)計(jì)算攻擊的可能性。缺省情況下,PHP使用一個(gè)2個(gè)字符的DES干擾串,如果你的系統(tǒng)使用的是MD5(我將在以后介紹MD5算法),它會(huì)使用一個(gè)12個(gè)字符的干擾串。順便說(shuō)一下,可以通過(guò)執(zhí)行下面的命令發(fā)現(xiàn)系統(tǒng)將要使用的干擾串的長(zhǎng)度: print "My system salt size is: ". CRYPT_SALT_LENGTH; ??? 系統(tǒng)也可能支持其他的加密算法。crypt()支持四種算法,下面是它支持的算法和相應(yīng)的salt參數(shù)的長(zhǎng)度: 算法 Salt長(zhǎng)度 CRYPT_STD_DES 2-character (Default) CRYPT_EXT_DES 9-character CRYPT_MD5 12-character beginning with $1$ CRYPT_BLOWFISH 16-character beginning with $2$ 用crypt()實(shí)現(xiàn)用戶(hù)身份驗(yàn)證 ??? 作為crypt()函數(shù)的一個(gè)例子,考慮這樣一種情況,你希望創(chuàng)建一段PHP腳本程序限制對(duì)一個(gè)目錄的訪問(wèn),只允許能夠提供正確的用戶(hù)名和口令的用戶(hù)訪問(wèn)這一目錄。我將把資料存儲(chǔ)在我喜歡的數(shù)據(jù)庫(kù)MySQL的一個(gè)表中。下面我們以創(chuàng)建這個(gè)被稱(chēng)作members的表開(kāi)始我們的例子: mysql>CREATE TABLE members (
??? ->username CHAR(14) NOT NULL,
??? ->password CHAR(32) NOT NULL,
??? ->PRIMARY KEY(username)
??? ->); ??? 然后,我們假定下面的數(shù)據(jù)已經(jīng)存儲(chǔ)在該表中: 用戶(hù)名 密碼 clark keloD1C377lKE bruce ba1T7vnz9AWgk peter paLUvRWsRLZ4U ??? 這些加密的口令對(duì)應(yīng)的明碼分別是kent、banner和parker。注意一下每個(gè)口令的前二個(gè)字母,這是因?yàn)槲沂褂昧讼旅娴拇a,根據(jù)口令的前二個(gè)字母創(chuàng)建干擾串的: $enteredPassword.
$salt = substr($enteredPassword, 0, 2);
$userPswd = crypt($enteredPassword, $salt);
// $userPswd然后就和用戶(hù)名一起存儲(chǔ)在MySQL中 ??? 我將使用Apache的口令-應(yīng)答認(rèn)證配置提示用戶(hù)輸入用戶(hù)名和口令,一個(gè)鮮為人知的有關(guān)PHP的信息是,它可以把Apache的口令-應(yīng)答系統(tǒng)輸入的用戶(hù)名和口令識(shí)別為$PHP_AUTH_USER和$PHP_AUTH_PW,我將在身份驗(yàn)證腳本中用到這二個(gè)變量。花一些時(shí)間仔細(xì)閱讀下面的腳本,多注意一下其中的解釋?zhuān)员愀玫乩斫庀旅娴拇a: crypt()和Apache的口令-應(yīng)答驗(yàn)證系統(tǒng)的應(yīng)用
$host = "localhost";
$user = "zorro";
$pswd = "hellodolly";
$db = "users";
// Set authorization to False
$authorization = 0;
// Verify that user has entered username and password
if (isset($PHP_AUTH_USER) && isset($PHP_AUTH_PW)) :
mysql_pconnect($host, $user, $pswd) or die("Can't connect to MySQL
server!");
mysql_select_db($db) or die("Can't select database!");
// Perform the encryption
$salt = substr($PHP_AUTH_PW, 0, 2);
$encrypted_pswd = crypt($PHP_AUTH_PW, $salt);
// Build the query
$query = "SELECT username FROM members WHERE
username = '$PHP_AUTH_USER' AND
password = '$encrypted_pswd'";
// Execute the query
if (mysql_numrows(mysql_query($query)) == 1) :
$authorization = 1;
endif;
endif;
// confirm authorization
if (! $authorization) :
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
print "You are unauthorized to enter this area.";
exit;
else :
print "This is the secret data!";
endif;
?> ??? 上面就是一個(gè)核實(shí)用戶(hù)訪問(wèn)權(quán)限的簡(jiǎn)單身份驗(yàn)證系統(tǒng)。在使用crypt()保護(hù)重要的機(jī)密資料時(shí),記住在缺省狀態(tài)下使用的crypt()并不是最安全的,只能用在對(duì)安全性要求較低的系統(tǒng)中,如果需要較高的安全性能,就需要我在本篇文章的后面介紹的算法。 ??? 下面我將介紹另一個(gè)PHP支持的函數(shù)━━md5(),這一函數(shù)使用MD5散列算法,它有幾種很有趣的用法值得一提: 混編 ??? 一個(gè)混編函數(shù)可以將一個(gè)可變長(zhǎng)度的信息變換為具有固定長(zhǎng)度被混編過(guò)的輸出,也被稱(chēng)作“信息文摘”。這是十分有用的,因?yàn)橐粋€(gè)固定長(zhǎng)度的字符串可以用來(lái)檢查文件的完整性和驗(yàn)證數(shù)字簽名以及用戶(hù)身份驗(yàn)證。由于它適合于PHP,PHP內(nèi)置的md5()混編函數(shù)將把一個(gè)可變長(zhǎng)度的信息轉(zhuǎn)換為128位(32個(gè)字符)的信息文摘?;炀幍囊粋€(gè)有趣的特點(diǎn)是不能通過(guò)分析混編后的信息得到原來(lái)的明碼,因?yàn)榛炀幒蟮慕Y(jié)果與原來(lái)的明碼內(nèi)容沒(méi)有依賴(lài)關(guān)系。 即便只改變一個(gè)字符串中的一個(gè)字符,也將使得MD5混編算法計(jì)算出二個(gè)截然不同的結(jié)果。我們首先來(lái)看下表的內(nèi)容及其相應(yīng)的結(jié)果: 使用md5()混編字符串 $msg = "This is some message that I just wrote";
$enc_msg = md5($msg);
print "hash: $enc_msg ";
?> ??? 結(jié)果:hash: 81ea092649ca32b5ba375e81d8f4972c ??? 注意,結(jié)果的長(zhǎng)度為32個(gè)字符。再來(lái)看一下下面的表,其中的$msg的值有了一點(diǎn)微小的變化: 使用md5()對(duì)一個(gè)稍微變化的字符串進(jìn)行混編 //注意,message中少了一個(gè)s
$msg = "This is some mesage that I just wrote";
$enc_msg = md5($msg);
print "hash2: $enc_msg
";
?> ??? 結(jié)果:hash2: e86cf511bd5490d46d5cd61738c82c0c ??? 可以發(fā)現(xiàn),盡管二個(gè)結(jié)果的長(zhǎng)度都是32個(gè)字符,但明文中一點(diǎn)微小的變化使得結(jié)果發(fā)生了很大的變化,因此,混編和md5()函數(shù)是檢查數(shù)據(jù)中微小變化的一個(gè)很好的工具。 ??? 盡管crypt()和md5()各有用處,但二者在功能上都受到一定的限制。在下面的部分中,我們將介紹二個(gè)非常有用的被稱(chēng)作Mcrypt和Mhash的PHP擴(kuò)展,將大大拓展PHP用戶(hù)在加密方面的選擇。 ??? 盡管我們?cè)谏厦娴男」?jié)中說(shuō)明了單向加密的重要性,但有時(shí)我們可能需要在加密后,再把密碼數(shù)據(jù)還原成原來(lái)的數(shù)據(jù),幸運(yùn)的是,PHP通過(guò)Mcrypt擴(kuò)展庫(kù)的形式提供了這種可能性。 Mcrypt Mcrypt 2.5.7 Unix | Win32 ??? Mcrypt 2.4.7是一個(gè)功能強(qiáng)大的加密算法擴(kuò)展庫(kù),它包括有22種算法,其中就包括下面的幾種算法: Blowfish RC2 Safer-sk64 xtea Cast-256 RC4 Safer-sk128 DES RC4-iv Serpent Enigma Rijndael-128 Threeway Gost Rijndael-192 TripleDES LOKI97 Rijndael-256 Twofish PanamaSaferplus Wake 安裝: ??? 在標(biāo)準(zhǔn)的PHP軟件包中不包括Mcrypt,因此需要下載它,下載的地址為:ftp://argeas.cs-net.gr/pub/unix/mcrypt/。下載后,按照下面的方法進(jìn)行編譯,并把它擴(kuò)充在PHP中: 下載Mcrypt軟件包。 gunzipmcrypt-x.x.x.tar.gz tar -xvfmcrypt-x.x.x.tar ./configure --disable-posix-threads make make install cd to your PHP directory. ./configure -with-mcrypt=[dir] [--other-configuration-directives] make make install ??? 當(dāng)然了,根據(jù)你的要求和PHP安裝時(shí)與互聯(lián)網(wǎng)服務(wù)器軟件的關(guān)系,上面的過(guò)程可能需要作適當(dāng)?shù)男薷摹?使用Mcrypt ??? Mcrypt的優(yōu)點(diǎn)不僅僅在于其提供的加密算法較多,還在于它可以對(duì)數(shù)據(jù)進(jìn)行加/解密處理,此外,它還提供了35種處理數(shù)據(jù)用的函數(shù)。盡管對(duì)這些函數(shù)進(jìn)行詳細(xì)介紹已經(jīng)超出了這篇文章的范圍,我還是要就幾個(gè)典型的函數(shù)作一下簡(jiǎn)要的介紹。 ??? 首先,我將介紹如何使用Mcrypt擴(kuò)展庫(kù)對(duì)數(shù)據(jù)進(jìn)行加密,然后再介紹如何使用它進(jìn)行解密。下面的代碼對(duì)這一過(guò)程進(jìn)行了演示,首先是對(duì)數(shù)據(jù)進(jìn)行加密,然后在瀏覽器上顯示加密后的數(shù)據(jù),并將加密后的數(shù)據(jù)還原為原來(lái)的字符串,將它顯示在瀏覽器上。 使用Mcrypt對(duì)數(shù)據(jù)進(jìn)行加、解密
// Designate string to be encrypted
$string = "Applied Cryptography, by Bruce Schneier, is
a wonderful cryptography reference.";
// Encryption/decryption key
$key = "Four score and twenty years ago";
// Encryption Algorithm
$cipher_alg = MCRYPT_RIJNDAEL_128;
// Create the initialization vector for added security.
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg,
MCRYPT_MODE_ECB), MCRYPT_RAND);
// Output original string
print "Original string: $string
";
// Encrypt $string
$encrypted_string = mcrypt_encrypt($cipher_alg, $key,
$string, MCRYPT_MODE_CBC, $iv);
// Convert to hexadecimal and output to browser
print "Encrypted string: ".bin2hex($encrypted_string)."
";
$decrypted_string = mcrypt_decrypt($cipher_alg, $key,
$encrypted_string, MCRYPT_MODE_CBC, $iv);
print "Decrypted string: $decrypted_string";
?>
執(zhí)行上面的腳本將會(huì)產(chǎn)生下面的輸出:
Original string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.
Encrypted string: 02a7c58b1ebd22a9523468694b091e60411cc4dea8652bb8072 34fa06bbfb20e71ecf525f29df58e28f3d9bf541f7ebcecf62b c89fde4d8e7ba1e6cc9ea24850478c11742f5cfa1d23fe22fe8 bfbab5e
Decrypted string: Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.
??? 上面的代碼中二個(gè)最典型的函數(shù)是mcrypt_encrypt()和mcrypt_decrypt(),它們的用途是顯而易見(jiàn)的。我使用了“電報(bào)密碼本”模式,Mcrypt提供了幾種加密方式,由于每種加密方式都有可以影響密碼安全的特定字符,因此每種模式都需要了解。對(duì)于沒(méi)有接觸過(guò)密碼系統(tǒng)的讀者來(lái)說(shuō),可能對(duì)mcrypt_create_iv()函數(shù)更有興趣,盡管對(duì)這一函數(shù)進(jìn)行徹底的解釋已經(jīng)超出了本篇文章的范圍,但我仍然會(huì)提到它創(chuàng)建的初始化向量(hence, iv),這一向量可以使每條信息彼此獨(dú)立。盡管不是所有的模式都需要這一初始化變量,但如果在要求的模式中沒(méi)有提供這一變量,PHP就會(huì)給出警告信息。
Mhash擴(kuò)展庫(kù)
http://sourceforge.net/projects/mhash/
??? 0.8.3版的Mhash擴(kuò)展庫(kù)支持12種混編算法,仔細(xì)檢查Mhash v.0.8.3的頭文件mhash.h可以知道,它支持下面的混編算法:
CRC32 HAVAL160 MD5
CRC32B HAVAL192 RIPEMD160
GOST HAVAL224 SHA1
HAVAL128 HAVAL256 TIGER
安裝
??? 象Mcrypt一樣,Mhash也沒(méi)有包括在PHP軟件包中,對(duì)于非Windows用戶(hù)而言,下面是安裝過(guò)程:
下載Mhash擴(kuò)展庫(kù)
gunzipmhash-x.x.x.tar.gz
tar -xvfmhash-x.x.x.tar
./configure
make
make install
cd
$message = "These are the directions to the secret fort. Two steps left, three steps right, and cha chacha.";
$hashed_message = mhash($hash_alg, $message);
print "The hashed message is ". bin2hex($hashed_message);
?>
??? 執(zhí)行這一段腳本程序?qū)⒌玫较旅娴妮敵鼋Y(jié)果:The hashed message is 07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461
???? 在這里使用bin2hex()函數(shù)的目的是方便我們理解$hashed_message的輸出,這是因?yàn)榛炀幍慕Y(jié)果是二進(jìn)制格式,為了能夠?qū)⑺D(zhuǎn)化為易于理解的格式,必須將它轉(zhuǎn)換為十六進(jìn)制格式。
??? 需要注意的是,混編是單向功能,其結(jié)果不依賴(lài)輸入,因此可以公開(kāi)顯示這一信息。這一策略通常用于讓用戶(hù)比較下載文件和系統(tǒng)管理員提供的文件,以確保文件的完整性。
???? Mhash還有其他一些有用的函數(shù)。例如,我需要輸出一個(gè)Mhash支持的算法的名字,由于Mhash支持的所有算法的名字都以MHASH_開(kāi)頭,因此,可以通過(guò)執(zhí)行如下的代碼完成這一任務(wù):
$hash_alg = MHASH_TIGER;
print "This data has been hashed with the".mhash_get_hash_name($hashed_message)."hashing algorithm.";
?>
得到的輸出是:This data has been hashed with the TIGER hashing algorithm.
關(guān)于PHP和加密最后需要注意的一個(gè)問(wèn)題
??? 關(guān)于PHP和加密需要注意的最后的一個(gè)重要問(wèn)題是在服務(wù)器和客戶(hù)端之間傳輸?shù)臄?shù)據(jù)在傳輸過(guò)程中是不安全的!PHP是一種服務(wù)器端技術(shù),不能阻止數(shù)據(jù)在傳輸過(guò)程中泄密。因此,如果想實(shí)現(xiàn)一個(gè)完整的安全應(yīng)用,建議選用Apache-SSL或其他的安全服務(wù)器布置。
結(jié)論
??? 這篇文章介紹了PHP最有用的功能之一━━數(shù)據(jù)加密,不僅討論了PHP內(nèi)置的crypt() 和md5()加密函數(shù),還討論了用于數(shù)據(jù)加密的功能強(qiáng)大的擴(kuò)展庫(kù)━━Mcrypt和Mhash。在這篇文章最后,我需要指出的是,一個(gè)真正安全的PHP應(yīng)用還應(yīng)該包括安全的服務(wù)器,由于PHP是一種服務(wù)器端的技術(shù),因此,在數(shù)據(jù)由客戶(hù)端向服務(wù)器端進(jìn)行傳輸時(shí),它不能保證數(shù)據(jù)的安全。

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)

Common problems and solutions for PHP variable scope include: 1. The global variable cannot be accessed within the function, and it needs to be passed in using the global keyword or parameter; 2. The static variable is declared with static, and it is only initialized once and the value is maintained between multiple calls; 3. Hyperglobal variables such as $_GET and $_POST can be used directly in any scope, but you need to pay attention to safe filtering; 4. Anonymous functions need to introduce parent scope variables through the use keyword, and when modifying external variables, you need to pass a reference. Mastering these rules can help avoid errors and improve code stability.

To safely handle PHP file uploads, you need to verify the source and type, control the file name and path, set server restrictions, and process media files twice. 1. Verify the upload source to prevent CSRF through token and detect the real MIME type through finfo_file using whitelist control; 2. Rename the file to a random string and determine the extension to store it in a non-Web directory according to the detection type; 3. PHP configuration limits the upload size and temporary directory Nginx/Apache prohibits access to the upload directory; 4. The GD library resaves the pictures to clear potential malicious data.

There are three common methods for PHP comment code: 1. Use // or # to block one line of code, and it is recommended to use //; 2. Use /.../ to wrap code blocks with multiple lines, which cannot be nested but can be crossed; 3. Combination skills comments such as using /if(){}/ to control logic blocks, or to improve efficiency with editor shortcut keys, you should pay attention to closing symbols and avoid nesting when using them.

AgeneratorinPHPisamemory-efficientwaytoiterateoverlargedatasetsbyyieldingvaluesoneatatimeinsteadofreturningthemallatonce.1.Generatorsusetheyieldkeywordtoproducevaluesondemand,reducingmemoryusage.2.Theyareusefulforhandlingbigloops,readinglargefiles,or

The key to writing PHP comments is to clarify the purpose and specifications. Comments should explain "why" rather than "what was done", avoiding redundancy or too simplicity. 1. Use a unified format, such as docblock (/*/) for class and method descriptions to improve readability and tool compatibility; 2. Emphasize the reasons behind the logic, such as why JS jumps need to be output manually; 3. Add an overview description before complex code, describe the process in steps, and help understand the overall idea; 4. Use TODO and FIXME rationally to mark to-do items and problems to facilitate subsequent tracking and collaboration. Good annotations can reduce communication costs and improve code maintenance efficiency.

ToinstallPHPquickly,useXAMPPonWindowsorHomebrewonmacOS.1.OnWindows,downloadandinstallXAMPP,selectcomponents,startApache,andplacefilesinhtdocs.2.Alternatively,manuallyinstallPHPfromphp.netandsetupaserverlikeApache.3.OnmacOS,installHomebrew,thenrun'bre

In PHP, you can use square brackets or curly braces to obtain string specific index characters, but square brackets are recommended; the index starts from 0, and the access outside the range returns a null value and cannot be assigned a value; mb_substr is required to handle multi-byte characters. For example: $str="hello";echo$str[0]; output h; and Chinese characters such as mb_substr($str,1,1) need to obtain the correct result; in actual applications, the length of the string should be checked before looping, dynamic strings need to be verified for validity, and multilingual projects recommend using multi-byte security functions uniformly.

TolearnPHPeffectively,startbysettingupalocalserverenvironmentusingtoolslikeXAMPPandacodeeditorlikeVSCode.1)InstallXAMPPforApache,MySQL,andPHP.2)Useacodeeditorforsyntaxsupport.3)TestyoursetupwithasimplePHPfile.Next,learnPHPbasicsincludingvariables,ech
