一、前言
PHP5.5提供了許多新特性及Api函數,其中之一就是Password Hashing API(創建和校驗哈希密碼)。
它包含4個函數:password_get_info()、password_hash()、password_needs_rehash()、password_verify()。
在PHP5.5之前,我們對于密碼的加密可能更多的是采用md5或sha1之類的加密方式(沒人像CSDN那樣存明文吧。。),如:
echo md5("123456"); //輸出: e10adc3949ba59abbe56e057f20f883e
但是簡單的md5加密很容易通過字典的方式進行破解,隨便找個md5解密的網站就能獲取原始密碼。
二、Password Hashing API
php5.5提供的Password Hashing API就能很好的解決這些問題。
我們先來看password_hash()函數:
復制代碼 代碼如下:
string password_hash ( string $password , integer $algo [, array $options ])
復制代碼 代碼如下:
$pwd = "123456";
$hash = password_hash($pwd, PASSWORD_DEFAULT);
echo $hash;
復制代碼 代碼如下:
boolean password_verify ( string $password , string $hash )
它接收2個參數:密碼和哈希值,并返回布爾值。檢查之前生成的哈希值是否和密碼匹配:
復制代碼 代碼如下:
if (password_verify($pwd,'$2y$10$4kAu4FNGuolmRmSSHgKEMe3DbG5pm3diikFkiAKNh.Sf1tPbB4uo2')) {
echo "密碼正確";
} else {
echo "密碼錯誤";
}
基本上使用以上這2個函數就能安全的創建和校驗hash密碼了,還有另外2個API函數:
復制代碼 代碼如下:
password_get_info() //查看哈希值的相關信息
password_needs_rehash() //檢查一個hash值是否是使用特定算法及選項創建的
復制代碼 代碼如下:
var hash = crypto.createHash('md5').update("123456").digest('hex');
if(hash == "e10adc3949ba59abbe56e057f20f883e") console.log('密碼正確');
新聞熱點
疑難解答