Created
May 31, 2017 09:12
-
-
Save Clarence-pan/cf4e7afceb32da1020f8705efff871b2 to your computer and use it in GitHub Desktop.
一个安全地存储密码的方案
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User extends BaseModel | |
{ | |
const PASSWORD_COST = 11; // 这里配置bcrypt算法的代价,根据需要来随时升级 | |
const PASSWORD_ALGO = PASSWORD_BCRYPT; // 默认使用(现在也只能用)bcrypt | |
/** | |
* 验证密码是否正确 | |
* | |
* @param string $plainPassword 用户密码的明文 | |
* @param bool $autoRehash 是否自动重新计算下密码的hash值(如果有必要的话) | |
* @return bool | |
*/ | |
public function verifyPassword($plainPassword, $autoRehash = true) | |
{ | |
if (password_verify($plainPassword, $this->password)) { | |
if ($autoRehash && password_needs_rehash($this->password, self::PASSWORD_ALGO, ['cost' => self::PASSWORD_COST])) { | |
$this->updatePassword($plainPassword); | |
} | |
return true; | |
} | |
return false; | |
} | |
/** | |
* 更新密码 | |
* | |
* @param string $newPlainPassword | |
*/ | |
public function updatePassword($newPlainPassword) | |
{ | |
$this->password = password_hash($newPlainPassword, self::PASSWORD_ALGO, ['cost' => self::PASSWORD_COST]); | |
$this->save(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment