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

yipeiwu_com5年前PHP代码库

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

<?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 = '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;
  }
}

以上这篇详谈PHP中的密码安全性Password Hashing就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【宜配屋www.yipeiwu.com】。

相关文章

php将数据库中所有内容生成静态html文档的代码

复制代码 代码如下: <?php /* author:www.5dkx.com done:生成html文档 date:2009-10-27 */ require_once("con...

php购物网站支付paypal使用方法

详细参考: https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_htm...

PHP区块查询实现方法分析

本文实例讲述了PHP区块查询实现方法。分享给大家供大家参考,具体如下: 分块查询是介于顺序查询和折半查询之间的一种查询方法。 其实折半查询就是每次折半的分块查询,那么分块查询就是把数组分...

PHP控制反转(IOC)和依赖注入(DI)

先看一个例子: <?php class A { public $b; public $c; public function A() { //TODO }...

WordPress分页伪静态加html后缀

WordPress分页伪静态加html后缀

问题 当文章有分页的时候,WordPress生成的永久链接是page.html/2的形式,前面一段是文章的$link,后面的数字代表分页$number。那么问题来了,挖掘……不对,从逻辑...