您好,登錄后才能下訂單哦!
本篇內(nèi)容介紹了“PHP中的密碼加密方式實例”的有關(guān)知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領(lǐng)大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!
如果你還在用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;//可以確定該算法應(yīng)多復(fù)雜,進而確定生成哈希值將花費多長時間。(將此值視為更改算法本身重新運行的次數(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中的密碼加密方式實例”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識可以關(guān)注億速云網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。