首頁 > 後端開發 > php教程 > PHP中的密碼安全性Password Hashing詳解

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

墨辰丷
發布: 2023-03-28 07:10:02
原創
1883 人瀏覽過

這篇文章主要介紹PHP中的密碼安全性Password Hashing詳解,有興趣的朋友參考下,希望對大家有幫助。

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

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

#

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

<?php

 

//require &#39;password.php&#39;;

/**

 * 正确的密码是secret-password

 * $passwordHash 是hash 后存储的密码

 * password_verify()用于将用户输入的密码和数据库存储的密码比对。成功返回true,否则false

 */

$passwordHash = password_hash(&#39;secret-password&#39;, PASSWORD_DEFAULT);

echo $passwordHash;

if (password_verify(&#39;bad-password&#39;, $passwordHash)) {

  // Correct Password

  echo &#39;Correct Password&#39;;

} else {

  echo &#39;Wrong password&#39;;

  // Wrong password

}

登入後複製

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

<?php

class 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 = &#39;dbd014125a4bad51db85f27279f1040a&#39;;

  }

 

  // 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, [&#39;cost&#39; => 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, [&#39;cost&#39; => 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;

  }

}

登入後複製

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


相關推薦:

Auth使用salt和password進行使用者認證實例

詳解Laravel透過修改Auth使用salt和password認證

透過修改Laravel Auth使用salt和password進行認證使用者詳解

#

以上是PHP中的密碼安全性Password Hashing詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板