詳談PHP中的密碼安全性Password Hashing
更新時間:2017年02月04日 09:28:54 投稿:jingxian
下面小編就為大家?guī)硪黄斦凱HP中的密碼安全性Password Hashing。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
如果你還在用md5加密,建議看看下方密碼加密和驗證方式。
先看一個簡單的Password Hashing例子:
<?php
//require 'password.php';
/**
* 正確的密碼是secret-password
* $passwordHash 是hash 后存儲的密碼
* password_verify()用于將用戶輸入的密碼和數(shù)據(jù)庫存儲的密碼比對。成功返回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;//可以確定該算法應多復雜,進而確定生成哈希值將花費多長時間。(將此值視為更改算法本身重新運行的次數(shù),以減緩計算。)
// 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就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Thinkphp5和Thinkphp3的區(qū)別對比以及單字母函數(shù)對應的助手函數(shù)
TP5在很多方面相比TP3升級和提升。盡管TP3已經有一定的市場和用戶群體,但新項目還是建議使用TP5。thinkphp3.2中一些快捷大寫單字母函數(shù),比如 U(),I() , C(),M() , D() , W()等,這些在thinkphp5 中已經不再使用,而是改用助手函數(shù)來代替。2023-07-07
php實現(xiàn)統(tǒng)計目錄文件大小的函數(shù)
本文給大家介紹了使用php實現(xiàn)統(tǒng)計目錄文件大小的函數(shù),其主要的思路是通過遞歸遍歷目錄中的所有文件從而計算出文件總大小的,有需要的小伙伴可以參考下2015-12-12
PHP面向對象程序設計高級特性詳解(接口,繼承,抽象類,析構,克隆等)
這篇文章主要介紹了PHP面向對象程序設計高級特性,結合實例形式分析了php面向對象程序設計中所涉及的靜態(tài)屬性、常量屬性、接口、繼承、抽象類、析構、克隆等概念與使用技巧,需要的朋友可以參考下2016-12-12
PHP從零開始打造自己的MVC框架之路由類實現(xiàn)方法分析
這篇文章主要介紹了PHP從零開始打造自己的MVC框架之路由類實現(xiàn)方法,結合實例形式分析了MVC框架路由類的原理及定義方法,需要的朋友可以參考下2019-06-06

