LoginSignup
13
14

More than 5 years have passed since last update.

PHPでCrypt Blowfishを使ったハッシュ化

Posted at

PHPパスワードをハッシュ化する

phpで用意されている強力なハッシュ化アルゴリズムを使用して、ハッシュ化を行いたいと思います。

注意
php5.6より前では、パスワードをもう一度ハッシュ化して、ハッシュ値の検証をしますが、
php5.6以降では、ハッシュ値の比較にhash_equals()関数を用います。

Crypt Blowfish

強力なハッシュ方式

Saltの生成

Saltはパスワードをハッシュ化する時に、毎回生成します。

// $strから乱数で文字列を取得して、$saltにcryptのsaltを生成する
    $str  = array_merge(range('a', 'z'), range('0', '9'), range('A', 'Z'),array(".","/"));
    // ランダムな文字列を22文字取得
    $max  = 22;

    // Blowfishをハッシュ形式に指定、ストレッチ用のコストパラメータを指定
    $salt = "$2y$04$";

    for ($i = 1; $i <= $max; $i++) {
        $salt .= $str[rand(0, count($str)-1)];
    }

Blowfish形式で暗号化

    // ハッシュ化
    $hashedPassword = crypt($password, $salt);

ハッシュ値の照合(php5.6より前の場合)

   if(crypt($password, $hashedPassword)==$hashedPassword){
       // 照合成功
   }

$hashedPasswordをcrypt()関数で使用していることが、見た目上気持ち悪いですが、
この場合、crypt()関数が使用するのは最初に生成したsalt部分までになります。
salt以降は無視され、最初のハッシュ化の際に使用したsalt部分だけを使用します。

ハッシュ値の照合(php5.6)

if (hash_equals($hashedPassword, crypt($password, $hashedPassword)) {
   // 照合成功
}
13
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
14