程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长

+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

如何使用bcrypt在PHP中对密码进行哈希处理?

发布于2021-03-10 19:58     阅读(497)     评论(0)     点赞(20)     收藏(4)


我时不时听到“使用bcrypt在PHP中使用密码,bcrypt规则存储密码”的建议。

但是什么bcrypt呢?PHP不提供任何此类功能,维基百科对文件加密实用程序不屑一顾,而Web搜索仅显示了一些Blowfish用不同语言的实现。现在Blowfish也可以通过PHP在PHP中使用mcrypt,但这对存储密码有何帮助?河豚是一种通用密码,它通过两种方式起作用。如果可以加密,则可以解密。密码需要单向散列功能。

有什么解释?


解决方案


bcrypt是一种哈希算法,可通过硬件(通过可配置的回合数)进行扩展。它的缓慢性和多次回合确保了攻击者必须部署大量资金和硬件才能破解您的密码。加上每个密码的bcrypt需要盐),您可以确定,在没有可笑的资金或硬件的情况下,攻击实际上是不可行的。

bcrypt使用Eksblowfish算法对密码进行哈希处理。虽然EksblowfishBlowfish的加密阶段完全相同,但是Eksblowfish的密钥调度阶段可确保任何后续状态都取决于salt和密钥(用户密码),并且在不了解这两个状态的情况下无法对它们进行预先计算。由于存在这一关键差异,因此bcrypt是一种单向哈希算法。在不知道盐,四舍五入和密钥(密码)的情况下,您无法检索纯文本密码[来源]

如何使用bcrypt:

使用PHP> = 5.5-DEV

密码哈希函数现已直接内置到PHP> = 5.5中现在,您可以password_hash()用来创建bcrypt任何密码哈希值:

<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

// Usage 2:
$options = [
  'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C

要针对现有哈希值验证用户提供的密码,您可以这样使用password_verify()

<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';

if (password_verify('rasmuslerdorf', $hash)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

使用PHP> = 5.3.7,<5.5-DEV(也是RedHat PHP> = 5.3.3)

GitHub上有一个兼容性库兼容性库是根据最初用C编写的上述函数的源代码创建的,该提供相同的功能。安装兼容性库后,用法与上面相同(如果仍在5.3.x分支上,请减去简写数组表示法)。

使用PHP <5.3.7 (已弃用)

您可以使用crypt()函数来生成输入字符串的bcrypt散列。此类可以自动生成盐,并根据输入来验证现有哈希。如果您使用的PHP版本高于或等于5.3.7,则强烈建议您使用内置函数或compat库仅出于历史目的提供此替代方法。

class Bcrypt{
  private $rounds;

  public function __construct($rounds = 12) {
    if (CRYPT_BLOWFISH != 1) {
      throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
    }

    $this->rounds = $rounds;
  }

  public function hash($input){
    $hash = crypt($input, $this->getSalt());

    if (strlen($hash) > 13)
      return $hash;

    return false;
  }

  public function verify($input, $existingHash){
    $hash = crypt($input, $existingHash);

    return $hash === $existingHash;
  }

  private function getSalt(){
    $salt = sprintf('$2a$%02d$', $this->rounds);

    $bytes = $this->getRandomBytes(16);

    $salt .= $this->encodeBytes($bytes);

    return $salt;
  }

  private $randomState;
  private function getRandomBytes($count){
    $bytes = '';

    if (function_exists('openssl_random_pseudo_bytes') &&
        (strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
      $bytes = openssl_random_pseudo_bytes($count);
    }

    if ($bytes === '' && is_readable('/dev/urandom') &&
       ($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
      $bytes = fread($hRand, $count);
      fclose($hRand);
    }

    if (strlen($bytes) < $count) {
      $bytes = '';

      if ($this->randomState === null) {
        $this->randomState = microtime();
        if (function_exists('getmypid')) {
          $this->randomState .= getmypid();
        }
      }

      for ($i = 0; $i < $count; $i += 16) {
        $this->randomState = md5(microtime() . $this->randomState);

        if (PHP_VERSION >= '5') {
          $bytes .= md5($this->randomState, true);
        } else {
          $bytes .= pack('H*', md5($this->randomState));
        }
      }

      $bytes = substr($bytes, 0, $count);
    }

    return $bytes;
  }

  private function encodeBytes($input){
    // The following is code from the PHP Password Hashing Framework
    $itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

    $output = '';
    $i = 0;
    do {
      $c1 = ord($input[$i++]);
      $output .= $itoa64[$c1 >> 2];
      $c1 = ($c1 & 0x03) << 4;
      if ($i >= 16) {
        $output .= $itoa64[$c1];
        break;
      }

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 4;
      $output .= $itoa64[$c1];
      $c1 = ($c2 & 0x0f) << 2;

      $c2 = ord($input[$i++]);
      $c1 |= $c2 >> 6;
      $output .= $itoa64[$c1];
      $output .= $itoa64[$c2 & 0x3f];
    } while (true);

    return $output;
  }
}

您可以使用以下代码:

$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);

或者,您也可以使用Portable PHP Hashing Framework



所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.phpheidong.com/blog/article/110/b6f8c2b1a464134bcb0b/

来源:php黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

20 0
收藏该文
已收藏

评论内容:(最多支持255个字符)