创建的password_hash()
哈希需要通过 ̀password_verify()` 进行比较,因为相同密码的 2 个哈希并不总是相等(至少不使用 BCRYPT 或 ARGON2)。
<?php
$pass = 'foo';
var_dump(password_hash($pass, PASSWORD_BCRYPT) === password_hash($pass, PASSWORD_BCRYPT));
// bool(false)
var_dump(password_verify($pass, password_hash($pass, PASSWORD_BCRYPT)));
// bool(true)
有人(s7anley)做了一个Zend_Auth_Adapter_DbTable
使用 password_verify() 的扩展,这里是(供参考):
<?php
class Base_Auth_Adapter_BcryptDbTable extends Zend_Auth_Adapter_DbTable
{
/**
* @inheritdoc
*/
protected function _authenticateCreateSelect()
{
$dbSelect = clone $this->getDbSelect();
$dbSelect->from($this->_tableName)
->where($this->_zendDb->quoteIdentifier($this->_identityColumn, true) . ' = ?', $this->_identity);
return $dbSelect;
}
/**
* @inheritdoc
*/
protected function _authenticateValidateResult($resultIdentity)
{
$passwordCheck = password_verify($this->_credential, $resultIdentity[$this->_credentialColumn]);
if (!$passwordCheck) {
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID;
$this->_authenticateResultInfo['messages'][] = 'Supplied credential is invalid.';
return $this->_authenticateCreateAuthResult();
}
$this->_resultRow = $resultIdentity;
$this->_authenticateResultInfo['code'] = Zend_Auth_Result::SUCCESS;
$this->_authenticateResultInfo['messages'][] = 'Authentication successful.';
return $this->_authenticateCreateAuthResult();
}
}
类名显示为“Bcrypt”,但它适用于任何支持的算法password_hash()
。
你可以这样使用它:
$authAdapter = new Base_Auth_Adapter_BcryptDbTable($databaseAdapter, 'users', 'login', 'password');
$authAdapter
->setIdentity('my_username')
->setCredential('my_password') // "clear" password
// ->setCredentialTreatment(null) // Can't set any treatment on password (would be ignored)
;
// For any additional filtering of returned rows, use getDbSelect()
$authAdapter->getDbSelect()->where('active = "TRUE"');