你如何在PHP中使用bcrypt來哈希密碼

我偶爾會聽到「使用bcrypt在PHP中存儲密碼,bcrypt規則」的建議。php

可是什麼bcrypt?PHP不提供任何這樣的功能,維基百科關於文件加密實用程序的喋喋不休,Web搜索只是揭示了幾種不一樣語言的Blowfish實現。如今Blowfish也能夠經過PHP得到mcrypt,但這對於存儲密碼有什麼幫助?河豚是一種通用密碼,它有兩種工做方式。若是它能夠被加密,它能夠被解密。密碼須要單向散列函數。html

什麼是解釋?node


bcrypt是一種哈希算法,能夠經過硬件進行擴展(經過可配置的循環次數)。其緩慢和多輪確保攻擊者必須部署大量資金和硬件才能破解密碼。添加到每一個密碼bcrypt須要鹽),你能夠確定的是,一個攻擊其實是不可行的,沒有好笑的金額或硬件。git

bcrypt使用Eksblowfish算法來散列密碼。雖然EksblowfishBlowfish的加密階段徹底相同,但Eksblowfish的關鍵調度階段確保任何後續狀態都依賴salt和key(用戶密碼),而且在沒有二者都知道的狀況下不能預先計算狀態。因爲這個關鍵差別,bcrypt是一種單向哈希算法。若是不知道鹽,圓和密碼(密碼),則沒法檢索純文本密碼。[ 來源 ]github

如何使用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分支上,則減去速記數組表示法)。dom

使用PHP <5.3.7 (DEPRECATED)

您可使用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;
  }
}

你可使用這樣的代碼:ui


或者,您也可使用Portable PHP Hashing Framework$bcrypt = new Bcrypt(15);

$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
相關文章
相關標籤/搜索