PHP中的密碼安全性Password Hashing詳解

來源:互聯網
上載者:User
本篇文章主要介紹PHP中的密碼安全性Password Hashing詳解,感興趣的朋友參考下,希望對大家有所協助。

如果你還在用md5加密,建議看看下方密碼加密和驗證方式。

先看一個簡單的Password Hashing例子:

<?php//require 'password.php';/** * 正確的密碼是secret-password * $passwordHash 是hash 後儲存的密碼 * password_verify()用於將使用者輸入的密碼和資料庫儲存的密碼比對。成功返回true,否則false */$passwordHash = password_hash('secret-password', PASSWORD_DEFAULT);echo $passwordHash;if (password_verify('bad-password', $passwordHash)) {  // Correct Password  echo 'Correct Password';} else {  echo 'Wrong password';  // Wrong password}

下方代碼提供了一個完整的類比的 User 類,在這個類中,通過使用Password Hashing,既能安全地處理使用者的密碼,又能支援未來不斷變化的安全需求。

<?phpclass User{  // Store password options so that rehash & hash can share them:  const HASH = PASSWORD_DEFAULT;  const COST = 14;//可以確定該演算法應多複雜,進而確定產生雜湊值將花費多長時間。(將此值視為更改演算法本身重新啟動並執行次數,以減緩計算。)  // Internal data storage about the user:  public $data;  // Mock constructor:  public function __construct() {    // Read data from the database, storing it into $data such as:    // $data->passwordHash and $data->username    $this->data = new stdClass();    $this->data->passwordHash = 'dbd014125a4bad51db85f27279f1040a';  }  // Mock save functionality  public function save() {    // Store the data from $data back into the database  }  // Allow for changing a new password:  public function setPassword($password) {    $this->data->passwordHash = password_hash($password, self::HASH, ['cost' => self::COST]);  }  // Logic for logging a user in:  public function login($password) {    // First see if they gave the right password:    echo "Login: ", $this->data->passwordHash, "\n";    if (password_verify($password, $this->data->passwordHash)) {      // Success - Now see if their password needs rehashed      if (password_needs_rehash($this->data->passwordHash, self::HASH, ['cost' => self::COST])) {        // We need to rehash the password, and save it. Just call setPassword        $this->setPassword($password);        $this->save();      }      return true; // Or do what you need to mark the user as logged in.    }    return false;  }}

以上就是本文的全部內容,希望對大家的學習有所協助。


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.