本篇内容介绍了“PHP中的密码加密方式实例”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!
如果你还在用md5加密,建议看看下方密码加密和验证方式。
先看一个简单的Password Hashing例子:
<?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,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。
<?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中的密码加密方式实例”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注亿速云网站,小编将为大家输出更多高质量的实用文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。