国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home php教程 php手冊 PHP中的加密功能

PHP中的加密功能

Jun 13, 2016 pm 12:44 PM
php superior Function encryption hair exist status us data Life network important


數(shù)據(jù)加密在我們生活中的地位已經(jīng)越來越重要了,尤其是考慮到在網(wǎng)絡(luò)上發(fā)生的大量交易和傳輸?shù)拇罅繑?shù)據(jù)。如果對于采用安全措施有興趣的話,也一定會有興趣了解PHP提供的一系列安全功能。在本篇文章中,我們將介紹這些功能,提供一些基本的用法,以便你能夠為自己的應(yīng)用軟件中增加安全功能。 預(yù)備知識 ??? 在詳細介紹PHP的安全功能之前,我們需要花點時間來向沒有接觸過這方面內(nèi)容的讀者介紹一些有關(guān)密碼學的基本知識,如果對密碼學的基本概念已經(jīng)非常熟悉,就可以跳過去這一部分。 ??? 密碼學可以通俗地被描述為對加/解密的研究和實驗,加密是將易懂的資料轉(zhuǎn)換為不易懂資料的過程,解密則是將不易懂的資料轉(zhuǎn)換為原來易懂資料的過程。不易懂的資料被稱作密碼,易懂的資料被稱作明碼。 ??? 數(shù)據(jù)的加/解密都需要一定的算法,這些算法可以非常地簡單,如著名的凱撒碼,但當前的加密算法要相對復(fù)雜得多,其中一些利用現(xiàn)有的方法甚至是無法破譯的。 PHP的加密功能 ??? 只要有一點使用非Windows平臺經(jīng)驗的人可能對crypt()也相當熟悉,這一函數(shù)完成被稱作單向加密的功能,它可以加密一些明碼,但不能夠?qū)⒚艽a轉(zhuǎn)換為原來的明碼。盡管從表面上來看這似乎是一個沒有什么用處的功能,但它的確被廣泛用來保證系統(tǒng)密碼的完整性。因為,單向加密的口令一旦落入第三方人的手里,由于不能被還原為明文,因此也沒有什么大用處。在驗證用戶輸入的口令時,用戶的輸入采用的也是單向算法,如果輸入與存儲的經(jīng)加密后的口令相匹配,則輸入的口信一定是正確的。 ??? PHP同樣提供了使用其crypt()函數(shù)完成單向加密功能的可能性。我將在這里簡要地介紹該函數(shù): string crypt (string input_string [, string salt]) ??? 其中的input_string參數(shù)是需要加密的字符串,第二個可選的salt是一個位字串,它能夠影響加密的暗碼,進一步地排除被稱作預(yù)計算攻擊的可能性。缺省情況下,PHP使用一個2個字符的DES干擾串,如果你的系統(tǒng)使用的是MD5(我將在以后介紹MD5算法),它會使用一個12個字符的干擾串。順便說一下,可以通過執(zhí)行下面的命令發(fā)現(xiàn)系統(tǒng)將要使用的干擾串的長度: print "My system salt size is: ". CRYPT_SALT_LENGTH; ??? 系統(tǒng)也可能支持其他的加密算法。crypt()支持四種算法,下面是它支持的算法和相應(yīng)的salt參數(shù)的長度: 算法 Salt長度 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()實現(xiàn)用戶身份驗證 ??? 作為crypt()函數(shù)的一個例子,考慮這樣一種情況,你希望創(chuàng)建一段PHP腳本程序限制對一個目錄的訪問,只允許能夠提供正確的用戶名和口令的用戶訪問這一目錄。我將把資料存儲在我喜歡的數(shù)據(jù)庫MySQL的一個表中。下面我們以創(chuàng)建這個被稱作members的表開始我們的例子: mysql>CREATE TABLE members (
??? ->username CHAR(14) NOT NULL,
??? ->password CHAR(32) NOT NULL,
??? ->PRIMARY KEY(username)
??? ->); ??? 然后,我們假定下面的數(shù)據(jù)已經(jīng)存儲在該表中: 用戶名 密碼 clark keloD1C377lKE bruce ba1T7vnz9AWgk peter paLUvRWsRLZ4U ??? 這些加密的口令對應(yīng)的明碼分別是kent、banner和parker。注意一下每個口令的前二個字母,這是因為我使用了下面的代碼,根據(jù)口令的前二個字母創(chuàng)建干擾串的: $enteredPassword.
$salt = substr($enteredPassword, 0, 2);
$userPswd = crypt($enteredPassword, $salt);
// $userPswd然后就和用戶名一起存儲在MySQL中 ??? 我將使用Apache的口令-應(yīng)答認證配置提示用戶輸入用戶名和口令,一個鮮為人知的有關(guān)PHP的信息是,它可以把Apache的口令-應(yīng)答系統(tǒng)輸入的用戶名和口令識別為$PHP_AUTH_USER和$PHP_AUTH_PW,我將在身份驗證腳本中用到這二個變量?;ㄒ恍r間仔細閱讀下面的腳本,多注意一下其中的解釋,以便更好地理解下面的代碼: crypt()和Apache的口令-應(yīng)答驗證系統(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;

?> ??? 上面就是一個核實用戶訪問權(quán)限的簡單身份驗證系統(tǒng)。在使用crypt()保護重要的機密資料時,記住在缺省狀態(tài)下使用的crypt()并不是最安全的,只能用在對安全性要求較低的系統(tǒng)中,如果需要較高的安全性能,就需要我在本篇文章的后面介紹的算法。 ??? 下面我將介紹另一個PHP支持的函數(shù)━━md5(),這一函數(shù)使用MD5散列算法,它有幾種很有趣的用法值得一提: 混編 ??? 一個混編函數(shù)可以將一個可變長度的信息變換為具有固定長度被混編過的輸出,也被稱作“信息文摘”。這是十分有用的,因為一個固定長度的字符串可以用來檢查文件的完整性和驗證數(shù)字簽名以及用戶身份驗證。由于它適合于PHP,PHP內(nèi)置的md5()混編函數(shù)將把一個可變長度的信息轉(zhuǎn)換為128位(32個字符)的信息文摘?;炀幍囊粋€有趣的特點是不能通過分析混編后的信息得到原來的明碼,因為混編后的結(jié)果與原來的明碼內(nèi)容沒有依賴關(guān)系。 即便只改變一個字符串中的一個字符,也將使得MD5混編算法計算出二個截然不同的結(jié)果。我們首先來看下表的內(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é)果的長度為32個字符。再來看一下下面的表,其中的$msg的值有了一點微小的變化: 使用md5()對一個稍微變化的字符串進行混編 //注意,message中少了一個s
$msg = "This is some mesage that I just wrote";
$enc_msg = md5($msg);
print "hash2: $enc_msg

";
?> ??? 結(jié)果:hash2: e86cf511bd5490d46d5cd61738c82c0c ??? 可以發(fā)現(xiàn),盡管二個結(jié)果的長度都是32個字符,但明文中一點微小的變化使得結(jié)果發(fā)生了很大的變化,因此,混編和md5()函數(shù)是檢查數(shù)據(jù)中微小變化的一個很好的工具。 ??? 盡管crypt()和md5()各有用處,但二者在功能上都受到一定的限制。在下面的部分中,我們將介紹二個非常有用的被稱作Mcrypt和Mhash的PHP擴展,將大大拓展PHP用戶在加密方面的選擇。 ??? 盡管我們在上面的小節(jié)中說明了單向加密的重要性,但有時我們可能需要在加密后,再把密碼數(shù)據(jù)還原成原來的數(shù)據(jù),幸運的是,PHP通過Mcrypt擴展庫的形式提供了這種可能性。 Mcrypt Mcrypt 2.5.7 Unix | Win32 ??? Mcrypt 2.4.7是一個功能強大的加密算法擴展庫,它包括有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 安裝: ??? 在標準的PHP軟件包中不包括Mcrypt,因此需要下載它,下載的地址為:ftp://argeas.cs-net.gr/pub/unix/mcrypt/。下載后,按照下面的方法進行編譯,并把它擴充在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 ??? 當然了,根據(jù)你的要求和PHP安裝時與互聯(lián)網(wǎng)服務(wù)器軟件的關(guān)系,上面的過程可能需要作適當?shù)男薷摹?使用Mcrypt ??? Mcrypt的優(yōu)點不僅僅在于其提供的加密算法較多,還在于它可以對數(shù)據(jù)進行加/解密處理,此外,它還提供了35種處理數(shù)據(jù)用的函數(shù)。盡管對這些函數(shù)進行詳細介紹已經(jīng)超出了這篇文章的范圍,我還是要就幾個典型的函數(shù)作一下簡要的介紹。 ??? 首先,我將介紹如何使用Mcrypt擴展庫對數(shù)據(jù)進行加密,然后再介紹如何使用它進行解密。下面的代碼對這一過程進行了演示,首先是對數(shù)據(jù)進行加密,然后在瀏覽器上顯示加密后的數(shù)據(jù),并將加密后的數(shù)據(jù)還原為原來的字符串,將它顯示在瀏覽器上。 使用Mcrypt對數(shù)據(jù)進行加、解密
// 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í)行上面的腳本將會產(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. ??? 上面的代碼中二個最典型的函數(shù)是mcrypt_encrypt()和mcrypt_decrypt(),它們的用途是顯而易見的。我使用了“電報密碼本”模式,Mcrypt提供了幾種加密方式,由于每種加密方式都有可以影響密碼安全的特定字符,因此每種模式都需要了解。對于沒有接觸過密碼系統(tǒng)的讀者來說,可能對mcrypt_create_iv()函數(shù)更有興趣,盡管對這一函數(shù)進行徹底的解釋已經(jīng)超出了本篇文章的范圍,但我仍然會提到它創(chuàng)建的初始化向量(hence, iv),這一向量可以使每條信息彼此獨立。盡管不是所有的模式都需要這一初始化變量,但如果在要求的模式中沒有提供這一變量,PHP就會給出警告信息。 Mhash擴展庫 http://sourceforge.net/projects/mhash/ ??? 0.8.3版的Mhash擴展庫支持12種混編算法,仔細檢查Mhash v.0.8.3的頭文件mhash.h可以知道,它支持下面的混編算法: CRC32 HAVAL160 MD5 CRC32B HAVAL192 RIPEMD160 GOST HAVAL224 SHA1 HAVAL128 HAVAL256 TIGER 安裝 ??? 象Mcrypt一樣,Mhash也沒有包括在PHP軟件包中,對于非Windows用戶而言,下面是安裝過程: 下載Mhash擴展庫 gunzipmhash-x.x.x.tar.gz tar -xvfmhash-x.x.x.tar ./configure make make install cd ./configure -with-mhash=[dir] [--other-configuration-directives] make make install ??? 象Mcrypt一樣,根據(jù)PHP在互聯(lián)網(wǎng)服務(wù)器軟件上的安裝方式,可能需要對Mhash進行其他的配置。 ??? 對于Windows用戶而言,http://www.php4win.de中有一個很好的包括Mhash擴展庫在內(nèi)的PHP軟件包。只要下載并進行解壓縮,然后根據(jù)其中的readme.first文檔中的指令進行安裝即可。 使用Mhash ??? 對信息進行混編非常簡單,看一下下面的例子: $hash_alg = MHASH_TIGER;
$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的輸出,這是因為混編的結(jié)果是二進制格式,為了能夠?qū)⑺D(zhuǎn)化為易于理解的格式,必須將它轉(zhuǎn)換為十六進制格式。 ??? 需要注意的是,混編是單向功能,其結(jié)果不依賴輸入,因此可以公開顯示這一信息。這一策略通常用于讓用戶比較下載文件和系統(tǒng)管理員提供的文件,以確保文件的完整性。 ???? Mhash還有其他一些有用的函數(shù)。例如,我需要輸出一個Mhash支持的算法的名字,由于Mhash支持的所有算法的名字都以MHASH_開頭,因此,可以通過執(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和加密最后需要注意的一個問題 ??? 關(guān)于PHP和加密需要注意的最后的一個重要問題是在服務(wù)器和客戶端之間傳輸?shù)臄?shù)據(jù)在傳輸過程中是不安全的!PHP是一種服務(wù)器端技術(shù),不能阻止數(shù)據(jù)在傳輸過程中泄密。因此,如果想實現(xiàn)一個完整的安全應(yīng)用,建議選用Apache-SSL或其他的安全服務(wù)器布置。 結(jié)論 ??? 這篇文章介紹了PHP最有用的功能之一━━數(shù)據(jù)加密,不僅討論了PHP內(nèi)置的crypt() 和md5()加密函數(shù),還討論了用于數(shù)據(jù)加密的功能強大的擴展庫━━Mcrypt和Mhash。在這篇文章最后,我需要指出的是,一個真正安全的PHP應(yīng)用還應(yīng)該包括安全的服務(wù)器,由于PHP是一種服務(wù)器端的技術(shù),因此,在數(shù)據(jù)由客戶端向服務(wù)器端進行傳輸時,它不能保證數(shù)據(jù)的安全。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Why We Comment: A PHP Guide Why We Comment: A PHP Guide Jul 15, 2025 am 02:48 AM

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

How to Install PHP on Windows How to Install PHP on Windows Jul 15, 2025 am 02:46 AM

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

PHP Syntax: The Basics PHP Syntax: The Basics Jul 15, 2025 am 02:46 AM

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

PHP 8 Installation Guide PHP 8 Installation Guide Jul 16, 2025 am 03:41 AM

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

What is PHP and What is it Used For? What is PHP and What is it Used For? Jul 16, 2025 am 03:45 AM

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

python if else example python if else example Jul 15, 2025 am 02:55 AM

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.

Your First PHP Script: A Practical Introduction Your First PHP Script: A Practical Introduction Jul 16, 2025 am 03:42 AM

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

How Do You Handle File Operations (Reading/Writing) in PHP? How Do You Handle File Operations (Reading/Writing) in PHP? Jul 16, 2025 am 03:48 AM

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

See all articles