1. Encrypt the password and verify whether the password transmitted by the client is correct
1. Encrypt the password
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);
2. Verify the password passed by the client to determine whether it is correct
//$password:客户端传递的明文密码,$hash:对密码进行加密后的哈希值 if (Yii::$app->getSecurity()->validatePassword($password, $hash)) { // 验证成功(密码正确) } else { // 验证失败(密码错误) }
2. Generate a pseudo-random data
When we reset the password, we often send an email to In the user's mailbox, give him a reset password. At this time, we can use Yii's pseudo-random data method to generate a pseudo-random data as a password for the user
//默认生成32为随机字符,可以指定位数生成指定位数的伪随机数 $key = Yii::$app->getSecurity()->generateRandomString();
3. Yii common data encryption and decryption
Common encryption methods in Yii include: encryptByPassword() and encryptByKey()
Common decryption methods in Yii include: decryptByPassword() and decryptByKey()
1. encryptByPassword() and decryptByPassword()
Encryption:
//$data:需要加密的信息,$secretKey:加密时使用的密钥(key) $encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
Decryption:
//$encryptedData:需要解密的信息,$secretKey:加密时使用的密钥(key) $data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);
2. encryptByKey() and decryptByKey()
Encryption:
//$data:需要加密的信息,$secretKey:加密时使用的密钥(key) $encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);
Decryption:
//$encryptedData:需要解密的信息,$secretKey:加密时使用的密钥(key) $data = Yii::$app->getSecurity()->decryptByKey($encryptedData, $secretKey);
Recommended tutorial: yii
The above is the detailed content of How yii implements data encryption and decryption. For more information, please follow other related articles on the PHP Chinese website!