This article mainly introduces the issues about encryption and decryption in yii2. It has certain reference value. Now I share it with everyone. Friends in need can refer to it
Preface
Yii provides convenient helper functions that allow you to encrypt and decrypt data using a security key. Data is transmitted through an encryption function so that only someone with the security key can decrypt it. For example, we need to store some information in our database, but we need to ensure that only someone with a security key can see it (even if the application's database is leaked).
As we all know, when we make programs, encryption and decryption are unavoidable topics. When using yii2 to develop applications, what convenient support for encryption and decryption (security) is built in? This article will reveal it to you.
Related environment
The source code location of the Security component is as follows
vendor/yiisoft/yii2/base/Security.phpThe Security component has a total of 15 public methods related to encryption and decryption (&encoding). Let’s make a list first.
##maskToken
unmaskToken
I think there are some you haven’t seen before. It doesn’t matter. Let’s learn about them one by one.
generateRandomString
The reason why I talk about generateRandomString first is because it is the most commonly used, at least for me.
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 & validatePassword
##generatePasswordHash & validatePassword are often used to encrypt user passwords and verify whether the password is correct. Since MD5 After it may be collided, when we use yii2 to develop applications, the generatePasswordHash function becomes the first choice to encrypt passwords, and it 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
Similar to generateRandomString, it generates a random string. The parameter is the length, which defaults to 32 bits. The difference is that generateRandomKey does not generate ASCII. Simply speaking, generateRandomString is approximately equal to base64_encode(generateRandomKey).
encryptByPassword & decryptByPassword
Encoding and decoding functions use a secret key to encode the 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, available under outer wrapper via base64_encode and base64_decode.
encryptByKey & decryptByKey
is also a set of encoding and decoding functions, which is faster than passing a password. The function is declared as
public function encryptByKey($data, $inputKey, $info = null){} public function decryptByKey($data, $inputKey, $info = null){}
encryptByKey & decryptByKey. There is a third parameter. For example, we can pass the member's ID, etc., so that this information will be used together with $inputKey. The key to encryption and decryption.
hkdf
Derive a key from the given input key using the standard HKDF algorithm. In PHP7, the hash_hkdf method is used, while in PHP7, the hash_hmac method is used.
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 solution generatePasswordHash.
hashData and validateData
#Sometimes in order to prevent the content from being tampered with, we need to mark the data, hashData and validateData It is the combination that completes this task. hashData is used to add data prefix to the original data, such as the following code
$result = Yii::$app->security->hashData("hello",'123456',false); // ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello
你看到了在hello的前面多了一组字符,这组字符会随着原始数据的不同而变化。这样我们就对数据进行了特殊的防止篡改标记,接下来是validateData上场了。
注意:hashData的第三个参数代表生成的哈希值是否为原始二进制格式. 如果为false, 则会生成小写十六进制数字.
validateData 对已经加了数据前缀的数据进行检测,如下代码
$result = Yii::$app->security->validateData("ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello",'123456',false); // hello
如果返回了原始的字符串则表示验证通过,否则会返回假。
validateData 函数的第三个参数应该与使用 hashData() 生成数据时的值相同. 它指示数据中的散列值是否是二进制格式. 如果为false, 则表示散列值仅由小写十六进制数字组成. 将生成十六进制数字.
compareString
可防止时序攻击的字符串比较,用法非常简单。
Yii::$app->security->compareString("abc",'abc');
结果为真则相等,否则不相等。
那么什么是时序攻击那?我来举一个简单的例子。
if($code == Yii::$app->request->get('code')){ }
上面的比较逻辑,两个字符串是从第一位开始逐一进行比较的,发现不同就立即返回 false,那么通过计算返回的速度就知道了大概是哪一位开始不同的,这样就实现了电影中经常出现的按位破解密码的场景。
而使用 compareString 比较两个字符串,无论字符串是否相等,函数的时间消耗是恒定的,这样可以有效的防止时序攻击。
maskToken && unmaskToken
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 Regarding encryption and decryption issues in yii2. For more information, please follow other related articles on the PHP Chinese website!