详谈PHP中的密码安全性Password Hashing
程序员文章站
2024-03-06 20:46:08
如果你还在用md5加密,建议看看下方密码加密和验证方式。
先看一个简单的password hashing例子:
如果你还在用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中的密码安全性password hashing就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。