如何在yii中生成盐?

如何在yii中生成盐?,yii,salt,Yii,Salt,我正在我的项目中进行用户管理,我需要在数据库中存储密码。我读到密码应该是密码和盐一起保存。然而,我似乎没有找到如何为每个新的用户生成随机salt。 有人吗 试试这样的东西 $salt = openssl_random_pseudo_bytes(22); $salt = '$2a$%13$' . strtr($salt, array('_' => '.', '~' => '/')); $password_hash = crypt($form->password, $salt);

我正在我的项目中进行
用户管理
,我需要在
数据库中存储
密码
。我读到
密码
应该是
密码
一起保存。然而,我似乎没有找到如何为每个新的
用户生成
随机salt

有人吗

试试这样的东西

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


与您的答案并不严格相关,但我使用了这个优秀的扩展,它消除了在Yii中创建和存储密码的所有猜测

Joe的答案非常好。实际上我建议使用YiiPassword(),因为它给了您很大的灵活性


但是,是的,当涉及到密码和安全性时,最好不要重新发明轮子。除非你真的很小心,否则很可能会出现安全问题

我郑重建议您使用。

试试
$this->salt=uniqid(“”,true)
并使用
$this->password=$this->hashPassword($this->password,$this->salt);}
用于salt加密用户密码

我不熟悉Yii,但实际上您应该能够使用PHP的本机函数生成散列,并使用该函数检查密码是否与散列匹配。此函数将处理所有棘手的部分,如生成安全的盐,并将盐包含在结果哈希中

// 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);
// 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);