详谈PHP中的密码安全性Password Hashing
如果你还在用md5加密,建议看看下方密码加密和验证方式。
先看一个简单的PasswordHashing例子:
<?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)){
//CorrectPassword
echo'CorrectPassword';
}else{
echo'Wrongpassword';
//Wrongpassword
}
下方代码提供了一个完整的模拟的User类,在这个类中,通过使用PasswordHashing,既能安全地处理用户的密码,又能支持未来不断变化的安全需求。
<?php
classUser
{
//Storepasswordoptionssothatrehash&hashcansharethem:
constHASH=PASSWORD_DEFAULT;
constCOST=14;//可以确定该算法应多复杂,进而确定生成哈希值将花费多长时间。(将此值视为更改算法本身重新运行的次数,以减缓计算。)
//Internaldatastorageabouttheuser:
public$data;
//Mockconstructor:
publicfunction__construct(){
//Readdatafromthedatabase,storingitinto$datasuchas:
//$data->passwordHashand$data->username
$this->data=newstdClass();
$this->data->passwordHash='dbd014125a4bad51db85f27279f1040a';
}
//Mocksavefunctionality
publicfunctionsave(){
//Storethedatafrom$databackintothedatabase
}
//Allowforchanginganewpassword:
publicfunctionsetPassword($password){
$this->data->passwordHash=password_hash($password,self::HASH,['cost'=>self::COST]);
}
//Logicforloggingauserin:
publicfunctionlogin($password){
//Firstseeiftheygavetherightpassword:
echo"Login:",$this->data->passwordHash,"\n";
if(password_verify($password,$this->data->passwordHash)){
//Success-Nowseeiftheirpasswordneedsrehashed
if(password_needs_rehash($this->data->passwordHash,self::HASH,['cost'=>self::COST])){
//Weneedtorehashthepassword,andsaveit.JustcallsetPassword
$this->setPassword($password);
$this->save();
}
returntrue;//Ordowhatyouneedtomarktheuserasloggedin.
}
returnfalse;
}
}
以上这篇详谈PHP中的密码安全性PasswordHashing就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持毛票票。