PHP函数crypt()的功能介绍

2009-12-9     作者:   编辑:崔晓帆        点击进入论坛
关键词:PHP  函数

  我们知道在PHP中有实现数据加密的功能,我们今天将为大家介绍的是其中一个可以实现数据加密功能的函数——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的口令-应答验证系统的应用

  1. < ?php
  2. $host = "localhost";
  3. $user = "zorro";
  4. $pswd = "hell odolly";
  5. $db = "users";
  6. // Set authorization to False
  7. $authorization = 0;
  8. // Verify that user has entered
    username and password
  9. if (isset($PHP_AUTH_USER) &&
    isset($PHP_AUTH_PW)) :
  10. mysql_pconnect($host, $user,
    $pswd) or die("Can\'t connect to MySQL
  11. server!");
  12. mysql_select_db($db) or die
    ("Can\'t select database!");
  13. // Perform the encryption
  14. $salt = substr($PHP_AUTH_PW, 0, 2);
  15. $encrypted_pswd = crypt($PHP_AUTH_PW, $salt);
  16. // Build the query
  17. $query = "SELECT username FROM members WHERE
  18. username = \'$PHP_AUTH_USER\' AND
  19. password = \'$encrypted_pswd\'";
  20. // Execute the query
  21. if (mysql_numrows(mysql_query($query)) == 1) :
  22. $authorization = 1;
  23. endif;
  24. endif;
  25. // confirm authorization
  26. if (! $authorization) :
  27. header(\'WWW-Authenticate:
    Basic
    realm="Private"\');
  28. header(\'HTTP/1.0 401 Unauthorized\');
  29. print "You are unauthorized
    to enter this area.";
  30. exit;
  31. else :
  32. print "This is the secret data!";
  33. endif;
  34. ?>

上面就是一个核实用户访问权限的简单身份验证系统。在使用PHP函数crypt()保护重要的机密资料时,记住在缺省状态下使用的PHP函数crypt()并不是最安全的,只能用在对安全性要求较低的系统中,如果需要较高的安全性能,就需要我在本篇文章的后面介绍的算法。

寻找产品:
姓       名: 电   话:
公       司: E-mail:
描       述: