Yii example code for data encryption and decryption

Time:2021-9-24

There are many data in Yii that we cannot store and display in plaintext, such as passwords and some important file information. At this time, we need to encrypt these information

1: Encrypt the password and verify whether the password transmitted by the client is correct

1: Encrypt password


$hash = Yii::$app->getSecurity()->generatePasswordHash($password);

2: Verify the password passed by the client to determine whether it is correct

//$password: the plaintext password passed by the client, $hash: the hash value after encrypting the password 
if (Yii::$app->getSecurity()->validatePassword($password, $hash)) { 
  //Verification succeeded (correct password) 
} else { 
  //Authentication failed (password error) 
}

2: Generate a pseudo-random data

When we reset the password, we often send an email to the user’s mailbox to give him a reset password. At this time, we can use Yii’s pseudo-random data method to generate a pseudo-random data for the user as the password

//The default generated 32 is random characters. You can specify the number of bits to generate a pseudo-random number of the specified number of bits 
$key = Yii::$app->getSecurity()->generateRandomString();

3: Yii common data encryption and decryption

Yii common encryption methods are: encryptbypassword() and encryptbykey()

Yii common decryption methods are: decryptbypassword() and decryptbykey()

1: Encryptbypassword() and decryptbypassword()

Encryption:

//$data: information to be encrypted, $secretkey: key used for encryption 
$encryptedData = Yii::$app->getSecurity()->encryptByPassword($data, $secretKey);

decrypt:

//$encrypteddata: information to be decrypted, $secretkey: key used for encryption (key) 
$data = Yii::$app->getSecurity()->decryptByPassword($encryptedData, $secretKey);

1: Encryptbykey() and decryptbykey()

Encryption:

//$data: information to be encrypted, $secretkey: key used for encryption 
$encryptedData = Yii::$app->getSecurity()->encryptByKey($data, $secretKey);

decrypt:

//$encrypteddata: information to be decrypted, $secretkey: key used for encryption (key) 
$data = Yii::$app->getSecurity()->decryptByKey($encryptedData, $secretKey);

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.