登录  /  注册

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

墨辰丷
发布: 2018-05-26 11:10:57
原创
1590人浏览过

本篇文章主要介绍php中的密码安全性password hashing详解,感兴趣的朋友参考下,希望对大家有所帮助。

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

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

<?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,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。

<?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中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
关于CSS思维导图的课件在哪? 课件
凡人来自于2024-04-16 10:10:18
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号