查看: 616|回复: 0

[PHP实例] 详谈PHP中的密码安全性Password Hashing

发表于 2017-11-25 09:40:26

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

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

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

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

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

以上这篇详谈PHP中的密码安全性Password Hashing就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持程序员之家。



回复

使用道具 举报

关闭

站长推荐上一条 /1 下一条