A salt is a random data string that is used as an input to hash a password. The salt and the password are concatenated and encrypted with a cryptographic hash function and the output is then stored in the database. This method can protect the passwords even when the database security has been compromised.
Below is a short demonstration of SALT implementation in YII.
Here is what you have to do:
Go to your components folder, find and open UserIdentity.php file. Here you have to declare a constant variable for the string length that is going to be your salt.
const SALT_LENGTH = 10;
Next you have to generate your hash password. You can use any random string as salt or key to generate the password.
Next you have to generate your hash password. You can use any random string as salt or key to generate the password.
//class UserIdentity extends CUserIdentity
public function hashPassword($phrase, $salt = null){
$key = 'Gf;B&yXL|beJUf-K*PPiU{wf|@9K9j5?d+YW}?VAZOS%e2c -:11ii<}ZM?PO!96';
if(is_null($sal))
{ $salt = substr(hash('sha512', $key), 0, self::SALT_LENGTH); }
else
{
$salt = substr($salt, 0, self::SALT_LENGTH);//if salt exists in DB
}
$r = hash('sha512', $salt . $key . $phrase);
return $r;
}
Next you have to validate your password. The function ValidatePassword would compare the generated salt password with the password stored in the database. For that go to your UserIdentity class, open the file user-identity.php and add the following:
class UserIdentity extends CUserIdentity
public function validatePassword($password, $username, $dbPassword){
return $this->hashPassword($password, $username) === $dbPassword;
}
In the end add this code to your authenticate function.
$record is object of current user record from db
if(!validatePassword($this->password, $this->username, $record->password))
{
$this->errorCode=self::ERROR_PASSWORD_INVALID;
}
No comments:
Post a Comment