PHPによるパスワードの生成と認証(CRYPT_BLOWFISH)
UserFrostingではパスワードの生成にpassword_hash関数(CRYPT_BLOWFISH)を採用しています。
このログインシステムとアプリ(FlexisipはMD5関数使用)のパスワード認証システムの整合性を図るため、PHPによるログインシステムのパスワード生成・認証方法について纏めます(UserFrostingまたはFlexisipのどちらかの認証方法を採用)。
https://learn.userfrosting.com/users/user-accounts#password
以下コマンドによりターミナルでPHPコードを実行します。
$ php -a
password_hash関数
https://www.php.net/manual/en/function.password-hash.php
password_hash ( string
$password
, int$algo
[, array$options
] ) : string
以下 int $algo
に該当する箇所に適用する定義済み定数です。
https://www.php.net/manual/en/password.constants.php
- PASSWORD_DEFAULT
- PASSWORD_BCRYPT - Use the CRYPT_BLOWFISH algorithm to create the hash. This will produce a standard crypt() compatible hash using the “$2y$” identifier. The result will always be a 60 character string, or FALSE on failure.
- PASSWORD_ARGON2I
- PASSWORD_ARGON2ID
ex)
php > $options=['cost' => 04];
php > echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
$2y$04$x3kiESnKtbj6/FdxUQzEE.vUhNdZP/124VsHrNU99dtxM3rXSKlFO
PASSWORD_BCRYPT(CRYPT_BLOWFISH)の詳細についてはPHPのcrypt関数を参照のこと。
https://www.php.net/manual/en/function.crypt.php
上記60文字のハッシュ出力は、
- $2y$:ハッシュアルゴリズム(CRYPT_BLOWFISH)
- 04$:ハッシュ回数(2^04=16回)
- x3kiESnKtbj6/FdxUQzEE.:ソルトsaltと呼ばれる22文字のランダムな文字列(自動生成)
を含んだ形で出力されます。
パスワードが同じでも生成されるハッシュ出力は異なります。同じコマンドを実行します。
php > echo password_hash("rasmuslerdorf", PASSWORD_BCRYPT, $options);
$2y$04$6XJn2jDzu/iWxOXobKGMPuxK77wCbSIyJDo1QPlQruqq9E5j.oaq6
パスワードとして保存される上記ハッシュ出力を、その都度変化させることでセキュリティを確保しています。パスワード認証の際には、次のpassword_verify関数により、上記項目1~3を含んだ60文字のハッシュ出力と平文のパスワード(“rasmuslerdorf”) をセットで指定することで正誤を判定します。
password_verify関数
https://www.php.net/manual/en/function.password-verify.php
正しい場合は1を出力します。
password_verify ( string $password , string $hash ) : bool
ex)
php > $hash='$2y$04$x3kiESnKtbj6/FdxUQzEE.vUhNdZP/124VsHrNU99dtxM3rXSKlFO';
php > echo password_verify('rasmuslerdorf', $hash);
1
php > $hash='$2y$04$6XJn2jDzu/iWxOXobKGMPuxK77wCbSIyJDo1QPlQruqq9E5j.oaq6';
php > echo password_verify('rasmuslerdorf', $hash);
1