最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
详谈PHP中的密码安全性Password Hashing
时间:2022-06-24 14:58:18 编辑:袖梨 来源:一聚教程网
如果你还在用md5加密,建议看看下方密码加密和验证方式。
先看一个简单的Password Hashing例子:
代码如下 | 复制代码 |
//require 'password.php'; /** * 正确的密码是secret-password * $passwordHash 是hash 后存储的密码 * password_verify()用于将用户输入的密码和数据库存储的密码比对。成功返回true,否则false */ $passwordHash= password_hash('secret-password', PASSWORD_DEFAULT); echo$passwordHash; if(password_verify('bad-password',$passwordHash)) { // Correct Password echo'Correct Password'; }else{ echo'Wrong password'; // Wrong password } |
下方代码提供了一个完整的模拟的 User 类,在这个类中,通过使用Password Hashing,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。
代码如下 | 复制代码 |
classUser { // Store password options so that rehash & hash can share them: constHASH = PASSWORD_DEFAULT; constCOST = 14;//可以确定该算法应多复杂,进而确定生成哈希值将花费多长时间。(将此值视为更改算法本身重新运行的次数,以减缓计算。)
// Internal data storage about the user: public$data;
// Mock constructor: publicfunction__construct() { // Read data from the database, storing it into $data such as: // $data->passwordHash and $data->username $this->data =newstdClass(); $this->data->passwordHash ='dbd014125a4bad51db85f27279f1040a'; }
// Mock save functionality publicfunctionsave() { // Store the data from $data back into the database }
// Allow for changing a new password: publicfunctionsetPassword($password) { $this->data->passwordHash = password_hash($password, self::HASH, ['cost'=> self::COST]); }
// Logic for logging a user in: publicfunctionlogin($password) { // First see if they gave the right password: echo"Login: ",$this->data->passwordHash,"n"; if(password_verify($password,$this->data->passwordHash)) { // Success - Now see if their password needs rehashed if(password_needs_rehash($this->data->passwordHash, self::HASH, ['cost'=> self::COST])) { // We need to rehash the password, and save it. Just call setPassword $this->setPassword($password); $this->save(); } returntrue;// Or do what you need to mark the user as logged in. } returnfalse; } } |
相关文章
- 人们熟悉的寄居蟹属于以下哪种分类 神奇海洋11月21日答案 11-21
- 第五人格11.22共研服有什么更新 11月22日共研服更新内容介绍 11-21
- 原神恰斯卡怎么培养 11-21
- 无期迷途四星装束是谁 11-21
- 王者荣耀帝丹高中校服怎么获得 11-21
- 光遇姆明季后续版本怎么玩 11-21