如果你还在用md5加密,建议看看下方密码加密和验证方式。
先看一个简单的Password Hashing例子:
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<?php
//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,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。
?
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
<?php
class User
{
// Store password options so that rehash & hash can share them:
const HASH = PASSWORD_DEFAULT;
const COST = 14;//可以确定该算法应多复杂,进而确定生成哈希值将花费多长时间。(将此值视为更改算法本身重新运行的次数,以减缓计算。)
// Internal data storage about the user:
public $data;
// Mock constructor:
public function __construct() {
// Read data from the database, storing it into $data such as:
// $data->passwordHash and $data->username
$this->data = new stdClass();
$this->data->passwordHash = 'dbd014125a4bad51db85f27279f1040a';
}
// Mock save functionality
public function save() {
// Store the data from $data back into the database
}
// Allow for changing a new password:
public function setPassword($password) {
$this->data->passwordHash = password_hash($password, self::HASH, ['cost' => self::COST]);
}
// Logic for logging a user in:
public function login($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();
}
return true; // Or do what you need to mark the user as logged in.
}
return false;
}
}
|
以上这篇详谈PHP中的密码安全性Password Hashing就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持快网idc。
相关文章
猜你喜欢
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
- 个人网站搭建:如何挑选具有弹性扩展能力的服务器? 2025-06-10
- 个人服务器网站搭建:如何选择适合自己的建站程序或框架? 2025-06-10
- 64M VPS建站:能否支持高流量网站运行? 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 53
-
2025-05-29 100
-
2025-05-27 83
-
2025-05-26 22
-
在CentOS7系统上编译安装MySQL 5.7.13步骤详解
2025-05-25 96
热门评论

