编程语言
首页 > 编程语言> > 如何在PHP中使用bcrypt进行散列密码?

如何在PHP中使用bcrypt进行散列密码?

作者:互联网

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

但什么是bcrypt? PHP不提供任何此类功能,维基百科关于文件加密实用程序的唠叨和Web搜索只是揭示了Blowfish在不同语言中的一些实现.现在Blowfish也可以通过mcrypt以PHP形式提供,但这对存储密码有何帮助? Blowfish是一种通用密码,它有两种工作方式.如果它可以加密,则可以解密.密码需要单向散列函数.

解释是什么?

解决方法:

bcrypt是一种散列算法,可以通过硬件进行扩展(通过可配置的轮数).它的缓慢和多轮确保攻击者必须部署大量资金和硬件才能破解您的密码.添加到每个密码salts(bcrypt REQUIRES盐),你可以确定攻击几乎是不可行的,没有可笑的资金或硬件.

bcrypt使用Eksblowfish算法来散列密码.虽然Eksblowfish和Blowfish的加密阶段完全相同,但Eksblowfish的关键计划阶段确保任何后续状态都依赖于盐和密钥(用户密码),并且在不知道两者的情况下都不能预先计算任何状态.由于这一关键差异,bcrypt是一种单向散列算法.如果不知道salt,rounds和key(密码),则无法检索纯文本密码. [Source]

如何使用bcrypt:

使用PHP> = 5.5-DEV

密码散列函数have now been built directly into 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)

基于最初用C编写的上述函数的源代码创建GitHub上的compatibility library,其提供相同的功能.安装兼容性库后,使用情况与上面相同(如果您仍在5.3.x分支上,则减去简写数组表示法).

使用PHP< 5.3.7(已弃用) 您可以使用crypt()函数生成输入字符串的bcrypt哈希值.此类可以自动生成salt并验证输入的现有哈希值.如果您使用的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.

标签:php,passwords,cryptography,bcrypt,password-protection
来源: https://codeday.me/bug/20190910/1802099.html