首页 > 开发 > PHP > 正文

详谈PHP中的密码安全性Password Hashing

2024-05-04 22:01:03
字体:大 中 小
来源:转载
供稿:网友

如果你还在用md5加密,建议看看下方密码加密和验证方式。

先看一个简单的Password Hashing例子:

  1. <?php 
  2.   
  3. //require 'password.php'; 
  4. /** 
  5.  * 正确的密码是secret-password 
  6.  * $passwordHash 是hash 后存储的密码 
  7.  * password_verify()用于将用户输入的密码和数据库存储的密码比对。成功返回true,否则false 
  8.  */ 
  9. $passwordHash= password_hash('secret-password', PASSWORD_DEFAULT); 
  10. echo$passwordHash; 
  11. if(password_verify('bad-password',$passwordHash)) { 
  12.   // Correct Password 
  13.   echo'Correct Password'; 
  14. }else{ 
  15.   echo'Wrong password'; 
  16.   // Wrong password 
  17. } 

下方代码提供了一个完整的模拟的 User 类,在这个类中,通过使用Password Hashing,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。

  1. <?php 
  2. classUser 
  3. { 
  4.   // Store password options so that rehash & hash can share them: 
  5.   constHASH = PASSWORD_DEFAULT; 
  6.   constCOST = 14;//可以确定该算法应多复杂,进而确定生成哈希值将花费多长时间。(将此值视为更改算法本身重新运行的次数,以减缓计算。) 
  7.   
  8.   // Internal data storage about the user: 
  9.   public$data; 
  10.   
  11.   // Mock constructor: 
  12.   publicfunction__construct() { 
  13.     // Read data from the database, storing it into $data such as: 
  14.     // $data->passwordHash and $data->username 
  15.     $this->data =newstdClass(); 
  16.     $this->data->passwordHash ='dbd014125a4bad51db85f27279f1040a'; 
  17.   } 
  18.   
  19.   // Mock save functionality 
  20.   publicfunctionsave() { 
  21.     // Store the data from $data back into the database 
  22.   } 
  23.   
  24.   // Allow for changing a new password: 
  25.   publicfunctionsetPassword($password) { 
  26.     $this->data->passwordHash = password_hash($password, self::HASH, ['cost'=> self::COST]); 
  27.   } 
  28.   
  29.   // Logic for logging a user in: 
  30.   publicfunctionlogin($password) { 
  31.     // First see if they gave the right password: 
  32.     echo"Login: ",$this->data->passwordHash,"/n"; 
  33.     if(password_verify($password,$this->data->passwordHash)) { 
  34.       // Success - Now see if their password needs rehashed 
  35.       if(password_needs_rehash($this->data->passwordHash, self::HASH, ['cost'=> self::COST])) { 
  36.         // We need to rehash the password, and save it. Just call setPassword 
  37.         $this->setPassword($password); 
  38.         $this->save(); 
  39.       } //Vevb.com 
  40.       returntrue;// Or do what you need to mark the user as logged in. 
  41.     } 
  42.     returnfalse; 
  43.   } 
  44. }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表