Home >Backend Development >PHP Tutorial >Introduction to yii2 encryption and decryption
This article mainly introduces the introduction to yii2 encryption and decryption, which has certain reference value. Now I share it with everyone. Friends in need can refer to it
Related environment
Operating system and IDE macOS 10.13.1 & PhpStorm2018.1.2
Software version PHP7.1.8 Yii2.0.14
at In yii2, the library that manages encryption and decryption is called Security. It exists as a yii2 component, so you can obtain and use it through Yii::$app->security.
The source code location of the Security component is as follows
vendor/yiisoft/yii2/base/Security.php
The Security component has a total of 15 public methods related to encryption and decryption (&encoding). Let’s make a list first.
encryptByPassword
encryptByKey
public function generateRandomString($length = 32){...}Generate a random string. The parameter $length represents the length of the string. The default is 32 bits. It is worth explaining that the value range of this string is [A-Za-z0-9_-]. generatePasswordHash & validatePasswordgeneratePasswordHash & validatePassword are often used to encrypt user passwords and verify whether the password is correct. Since MD5 may be collided, when we use yii2 to develop applications, the generatePasswordHash function Encrypting the password becomes the first choice, which calls the crypt function. General usage is as follows
// 使用generatePasswordHash为用户的密码加密,$hash存储到库中 $hash = Yii::$app->getSecurity()->generatePasswordHash($password); // 使用validatePassword对密码进行验证 if(Yii::$app->getSecurity()->validatePassword($password, $hash)){ // 密码正确 }else{ // 密码错误 }generateRandomKey is similar to
generateRandomKeyThe generated one is not ASCII. Simply put generateRandomString
is approximately equal to base64_encode(generateRandomKey). encryptByPassword & decryptByPassword
Encoding and decoding functions use a secret key to encode data, and then use this secret key to decode the encoded data. Example$dat = Yii::$app->security->encryptByPassword("hello","3166886"); echo Yii::$app->security->encryptByPassword($dat,"3166886");// hello
It should be noted that the encoded data obtained above is not ASCII and can be wrapped in the outer layer through base64_encode and base64_decode.
encryptByKey & decryptByKey
is also a set of encoding and decoding functions, which is faster than using passwords. The function declaration ispublic function encryptByKey($data, $inputKey, $info = null){} public function decryptByKey($data, $inputKey, $info = null){}
pbkdf2
Derive a key from the given password using the standard PBKDF2 algorithm. This method can be used for password encryption, but yii2 has a better password encryption solutionhashData and validateData
Sometimes in order to prevent the content from being tampered with, we need to mark the data. HashData and validateData are the combination to complete this task.hashData
is used toadd data prefix to the original data, such as the following code
$result = Yii::$app->security->hashData("hello",'123456',false); // ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhelloYou see an extra group in front of hello Characters, this set of characters will vary depending on the original data. In this way, we have specially marked the data to prevent tampering, and then validateData comes on stage. Note: The third parameter of hashData represents whether the generated hash value is in original binary format. If it is
false
, lowercase hexadecimal numbers will be generated.validateData
$result = Yii::$app->security->validateData("ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello",'123456',false); // helloIf the original string is returned, it means the verification is passed, otherwise it will return false. The third parameter of the validateData function should be the same value as when the data was generated using
hashData()
. It indicates whether the hash value in the data is in binary format. If false, means that the hash value consists only of lowercase hexadecimal digits. Hexadecimal digits will be generated.compareString
Yii::$app->security->compareString("abc",'abc');
if($code == Yii::$app->request->get('code')){ }In the above comparison logic, the two strings are compared one by one starting from the first digit. If they find a difference, false will be returned immediately. Then by calculating the return speed, you can know which digit starts to differ. , thus realizing the bit-by-bit password cracking scene that often appears in movies.
而使用 compareString 比较两个字符串,无论字符串是否相等,函数的时间消耗是恒定的,这样可以有效的防止时序攻击。
maskToken用于掩盖真实token且不可以压缩,同一个token最后生成了不同的随机令牌,在yii2的csrf功能上就使用了maskToken,原理并不复杂,我们看下源码。
public function maskToken($token){ $mask = $this->generateRandomKey(StringHelper::byteLength($token)); return StringHelper::base64UrlEncode($mask . ($mask ^ $token)); }
而unmaskToken目的也很明确,用于得到被maskToken掩盖的token。
接下来我们看一个例子代码
$token = Yii::$app->security->maskToken("123456"); echo Yii::$app->security->unmaskToken($token);// 结果为 123456
最后我们总结下
加密/解密: encryptByKey()、decryptByKey()、 encryptByPassword() 和 decryptByPassword();
使用标准算法的密钥推导: pbkdf2() 和 hkdf();
防止数据篡改: hashData() 和 validateData();
密码验证: generatePasswordHash() 和 validatePassword()
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Introduction to yii2 encryption and decryption. For more information, please follow other related articles on the PHP Chinese website!