Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend_Auth setCredentialTreatment

I'm using Zend_Auth with setCredentialTreatment to set the hash method and salt. I see all examples doing something like this, where the salt seems to be inserted as a text.

->setCredentialTreatment('SHA1(CONCAT(?,salt))'

but my salt is stored in the database. I could retrieve it first then use it in setCredentialTreatment but is there a way I could define it directly as a field name, so setCredentialTreatment would know to get it from that field? sort of like the way we define the field name for the username or password

->setCredentialColumn('password')

A side issue I'm having is that I'd like to use SHA512 not SHA1. Is this possible or is it not available? All the examples I see using SHA1.

I should say I'm fairly new to zend and am porting an existing application, so please go easy on me with the answers.

like image 856
jblue Avatar asked Sep 16 '10 10:09

jblue


1 Answers

The example you've given does use the salt as stored in the database. It will work as long as the salt is stored in each row in a field called 'salt'. If the salt was not in the DB and in a PHP variable instead, the code would be something more like:

->setCredentialTreatment("SHA1(CONCAT(?, '$salt'))")

As for using SHA512, this might be a little trickier. Assuming you're using MySQL, SHA1() in this case is a MySQL function, and MySQL does not have a function for SHA512 as far as I can tell, and neither does PHP (edit: I was wrong about the latter, see comments). So you'll have to implement your own PHP SHA512 function, load the salt for the user out of the DB first, hash the result and not do anything to the variable in setCredentialTreatment.

As the other answer suggested you might want to write your own Zend_Auth_Adapter for this. An auth adapter is a class that handles authentication, presumably at the moment you're using Zend_Auth_Adapter_DbTable. You can find some more info about auth adapters in the manual: http://framework.zend.com/manual/en/zend.auth.introduction.html

Here's an example:

class My_Auth_Adapter extends Zend_Auth_Adapter_DbTable
{
    public function authenticate()
    {
        // load salt for the given identity
        $salt = $this->_zendDb->fetchOne("SELECT salt FROM {$this->_tableName} WHERE {$this->_identityColumn} = ?", $this->_identity);
        if (!$salt) {
            // return 'identity not found' error
            return new Zend_Auth_Result(Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND, $this->_identity);
        }

        // create the hash using the password and salt
        $hash = ''; // SET THE PASSWORD HASH HERE USING $this->_credential and $salt

        // replace credential with new hash
        $this->_credential = $hash;

        // Zend_Auth_Adapter_DbTable can do the rest now
        return parent::authenticate();
    }
}
like image 156
Tim Fountain Avatar answered Nov 08 '22 10:11

Tim Fountain