Question

I'm working on user management in my project and I got to the part where I need to store the passwords in the database. I read that the password should be crypt with the salt and be kept together. However I didn't seem to find out how do I generate a random salt for each new user. Anyone?

Was it helpful?

Solution

I would seriously suggest you use CPasswordHelper.

OTHER TIPS

Try something like this

$salt = openssl_random_pseudo_bytes(22);
$salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/'));
$password_hash = crypt($form->password, $salt);

And

if ($password_hash === crypt($form->password, $password_hash))
    // password is correct
else
    // password is wrong

Source

Not strictly relevant to your answer, but I use this excellent extension Yii extension which takes all the guesswork out of creating and storing passwords in Yii

Joe's answer is pretty good. I'd actually recommend using YiiPassword (https://github.com/phpnode/YiiPassword) as it gives you a lot of flexibility.

But yes, when it comes to passwords and security, far better not to reinvent the wheel. The likelihood is that you'll end up with security issues unless you are really careful.

try $this -> salt = uniqid('',true); and use $this->password = $this->hashPassword($this->password, $this->salt);} for salt encrypting user`s password

I'm not familiar with Yii, but actually you should be able to use PHP's native function password_hash() to generate the hash, and the function password_verify() to check whether the password matches the hash. This function will handle all the tricky parts like generating a safe salt, and will include the salt in the resulting hash.

// Hash a new password for storing in the database.
// The function automatically generates a cryptographically safe salt.
$hashToStoreInDb = password_hash($password, PASSWORD_BCRYPT);

// Check if the hash of the entered login password, matches the stored hash.
// The salt and the cost factor will be extracted from $existingHashFromDb.
$isPasswordCorrect = password_verify($password, $existingHashFromDb);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top