PHP函数crypt()的功能介绍
我们知道在
中有实现数据加密的功能,我们今天将为大家介绍的是其中一个可以实现数据加密功能的函数——PHP函数crypt()。 作为PHP函数crypt()的一个例子,考虑这样一种情况,你希望创建一段PHP脚本程序限 制对一个目录的访问,只允许能够提供正确的用户名和口令的用户访问这一目录。
我将把资料存储在我喜欢的数据库MySQL的一个表中。下面我 们以创建这个被称作members的表开始我们的例子:
- mysql>CREATE TABLE members (
 - ->username CHAR(14) NOT NULL,
 - ->password CHAR(32) NOT NULL,
 - ->PRIMARY KEY(username)
 - ->);
 
然后,我们假定下面的数据已经存储在该表中:
用户名 密码
clark keloD1C377lKE
bruce ba1T7vnz9AWgk
peter paLUvRWsRLZ4U
PHP函数crypt()中的这些加密的口令对应的明码分别是kent、banner和parker。注意一下每个口令的前二个字母, 这是因为我使用了下面的代码,根据口令的前二个字母创建干扰串的:
- $enteredPassword.
 - $salt = substr($enteredPassword, 0, 2);
 - $userPswd = crypt($enteredPassword, $salt);
 - // $userPswd然后就和用户名一起存储在MySQL 中
 
我将使用Apache的口令-应答认证配置提示用户输入用户名和口令,一个鲜为人知的有关PHP的信息是,它可以把Apache 的口令-应答系统输入的用户名和口令识别为$PHP_AUTH_USER和$PHP_AUTH_PW,我将在身份验证脚本中用到这二个变量。花一些时间仔细阅读下 面的脚本,多注意一下其中的解释,以便更好地理解下面的代码:
PHP函数crypt()和Apache的口令-应答验证系统的应用
- < ?php
 - $host = "localhost";
 - $user = "zorro";
 - $pswd = "hell odolly";
 - $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("Cant connect to MySQL- server!");
 - mysql_select_db($db) or die
 
("Cant 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;
 - ?>
 
上面就是一个核实用户访问权限的简单身份验证系统。在使用PHP函数crypt()保护重要的机密资料时,记住在缺省状态下使用的PHP函数crypt()并不是最安全的,只能用在对安全性要求较低的系统中,如果需要较高的安全性能,就需要我在本篇文章的后面介绍的算法。
永久链接:http://www.phprm.com/frame/php1003706.html
转载随意!带上文章地址吧。