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

六月 06, 2019 | views
Comments 0

如果你还在用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 

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

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



zend