Home > Backend Development > PHP Tutorial > Introduction to yii2 encryption and decryption

Introduction to yii2 encryption and decryption

不言
Release: 2023-04-02 22:28:02
Original
2118 people have browsed it

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
Copy after login

The Security component has a total of 15 public methods related to encryption and decryption (&encoding). Let’s make a list first.

  1. encryptByPassword

  2. encryptByKey

  3. ##decryptByPassword

  4. decryptByKey

  5. hkdf

  6. pbkdf2

  7. hashData

  8. validateData

  9. generateRandomKey

  10. generateRandomString

  11. generatePasswordHash

  12. validatePassword

  13. ##compareString
  14. ##maskToken
  15. unmaskToken
  16. 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 say

generateRandomString

first is because it is the most commonly used, at least for me.

public function generateRandomString($length = 32){...}
Copy after login
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 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{
    // 密码错误
}
Copy after login
generateRandomKey

is similar to

generateRandomString

, generating a random string, the parameter is the length, the default is 32 bits, the difference is

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
Copy after login

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 is

public function encryptByKey($data, $inputKey, $info = null){}

public function decryptByKey($data, $inputKey, $info = null){}
Copy after login

encryptByKey & decryptByKey. There is a third parameter. For example, we can pass the member's ID, etc., so that this information will be used as the encryption and decryption key together with $inputKey.

hkdf

Derive a key from the given input key using the standard HKDF algorithm.

The hash_hkdf method is used in PHP7, and the hash_hmac method is used in PHP7.

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 are the combination to complete 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
Copy after login
You 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

Detect the data that has been added with the data prefix, as shown in the following code

$result = Yii::$app->security->validateData("ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello",'123456',false);
// hello
Copy after login
If 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

String comparison that prevents timing attacks, Usage is very simple.

Yii::$app->security->compareString("abc",'abc');
Copy after login

If the result is true, they are equal, otherwise they are not equal.

So what is a timing attack? Let me give you a simple example.

if($code == Yii::$app->request->get('code')){
    
}
Copy after login
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 && unmaskToken

maskToken用于掩盖真实token且不可以压缩,同一个token最后生成了不同的随机令牌,在yii2的csrf功能上就使用了maskToken,原理并不复杂,我们看下源码。

public function maskToken($token){
    $mask = $this->generateRandomKey(StringHelper::byteLength($token));
    return StringHelper::base64UrlEncode($mask . ($mask ^ $token));
}
Copy after login

而unmaskToken目的也很明确,用于得到被maskToken掩盖的token。

接下来我们看一个例子代码

$token = Yii::$app->security->maskToken("123456");
echo Yii::$app->security->unmaskToken($token);// 结果为 123456
Copy after login

最后我们总结下

  • 加密/解密: encryptByKey()、decryptByKey()、 encryptByPassword() 和 decryptByPassword();

  • 使用标准算法的密钥推导: pbkdf2() 和 hkdf();

  • 防止数据篡改: hashData() 和 validateData();

  • 密码验证: generatePasswordHash() 和 validatePassword()

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

Yii无法捕获到异常的解决方法

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template