Those things about encryption and decryption in yii2

  • 2021-10-15 09:56:20
  • OfStack

Preface

Yii provides handy help functions that allow you to encrypt and decrypt data with a secure key. Data is transmitted by encryption function, so that only those who have the security key can decrypt it. For example, we need to store some information in our database, but we need to make sure that only those who have the security key can see it (even if the application's database is compromised).

As we all know, when we do programs, encryption and decryption is an unavoidable topic. When using yii2 to develop applications, what are the built-in support for encryption and decryption (security) convenience? This article will reveal for you.

Related environment

Operating system and IDE macOS 10.13. 1 & PhpStorm2018.1.2 Software version PHP7.1. 8 Yii2.0. 14

In yii2, the library for managing encryption and decryption is called Security, which exists as an yii2 component, so you can use Yii:: $app- > security to get and use it.

The source code location of the Security component is as follows

vendor/yiisoft/yii2/base/Security.php

There are 15 Security components 1 with encryption and decryption ( & Coding), let's make a list first.

encryptByPassword encryptByKey decryptByPassword decryptByKey hkdf pbkdf2 hashData validateData generateRandomKey generateRandomString generatePasswordHash validatePassword compareString maskToken unmaskToken

I think there are some you haven't seen before. It doesn't matter. Let's get to know them.

generateRandomString

The reason why I started with generateRandomString is that it is most commonly used, at least I am.


public function generateRandomString($length = 32){...}

Generates a random string with the parameter $length representing the length of the string, which defaults to 32 bits. It is worth noting that the value of this string is in the range [A-Za-z0-9_-].

generatePasswordHash & validatePassword

generatePasswordHash & validatePassword is often used to encrypt user passwords and verify whether passwords are correct. Since MD5 may be collided, when we use yii2 to develop applications, generatePasswordHash function becomes the first choice to encrypt passwords, which calls crypt function.

The general usage of 1 is as follows


//  Use generatePasswordHash Encrypt the user's password, $hash Store in a library 
$hash = Yii::$app->getSecurity()->generatePasswordHash($password);

//  Use validatePassword Verify the password 
if(Yii::$app->getSecurity()->validatePassword($password, $hash)){
 //  Correct password 
}else{
 //  Password error 
}

generateRandomKey

Similar to generateRandomString, a random string is generated, the parameter is length, and the default is 32 bits. The difference is that generateRandomKey does not generate ASCII.

Simply put, generateRandomString is approximately equal to base64_encode (generateRandomKey).

encryptByPassword & decryptByPassword

Encoding and decoding function, using a secret key to encode the data, and then using this secret key to decode the encoded data.

Example


$dat = Yii::$app->security->encryptByPassword("hello","3166886");
echo Yii::$app->security->encryptByPassword($dat,"3166886");// hello

Note that the encoded data obtained through the above is not ASCII, but can be wrapped under the outer layer through base64_encode and base64_decode.

encryptByKey & decryptByKey

It is also a set of encoding and decoding functions, which is faster than that by password. Function is declared as


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

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

encryptByKey & There is a third parameter in decryptByKey, for example, we can pass the member's ID, etc., so that this information will be used as the key to encryption and decryption from $inputKey1.

hkdf

Derives 1 key from a given input key using the standard HKDF algorithm. The hash_hkdf method is used in PHP7 +, less than the hash_hmac method used in PHP7.

pbkdf2

Use the standard PBKDF2 algorithm to derive 1 key from the given password. This method can be used for password encryption, but yii2 has a better password encryption scheme 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 of this task.

hashData is used to prefix the original data, such as the following code


$result = Yii::$app->security->hashData("hello",'123456',false);
// ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello

You see an extra set of characters in front of hello, which will change with the original data. In this way, we put a special tamper-proof mark on the data, and then validateData came on.

Note: The third parameter of hashData represents whether the generated hash value is in the original binary format. If it is false, a lowercase 106 digit is generated.

validateData detects data that has been prefixed with data, as follows


$result = Yii::$app->security->validateData("ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello",'123456',false);
// hello

If the original string is returned, it means that the verification passed, otherwise it will return false.

The third parameter of the validateData function should be the same value as when the data is generated using hashData (). It indicates whether the hash value in the data is in binary format. If false, it means that the hash value consists only of lowercase 106-ary digits. 106-ary digits will be generated.

compareString

String comparison that can prevent timing attacks, and its usage is very simple.


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

If the result is true, it will be equal, otherwise it will not be equal.

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


if($code == Yii::$app->request->get('code')){
 
}

According to the above comparison logic, the two strings are compared one by one from the first bit, and the false will be returned immediately if the difference is found. Then, by calculating the return speed, we can know which bit is different, thus realizing the scene of cracking passwords by bit that often appears in movies.

Using compareString to compare two strings, regardless of whether the strings are equal or not, the time consumption of the function is constant, which can effectively prevent timing attacks.

maskToken & & unmaskToken

maskToken is used to cover up the real token and can not be compressed. The same token finally generates different random tokens. maskToken is used on the csrf function of yii2. The principle is not complicated. Let's look at the source code.


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

The purpose of unmaskToken is also clear, which is used to obtain token masked by maskToken.

Next, let's look at an example code


$token = Yii::$app->security->maskToken("123456");
echo Yii::$app->security->unmaskToken($token);//  The result is  123456

Finally, let's sum up

Encryption/decryption: encryptByKey (), decryptByKey (), encryptByPassword () and decryptByPassword (); Key derivation using standard algorithms: pbkdf2 () and hkdf (); Prevent data tampering: hashData () and validateData (); Password authentication: generatePasswordHash () and validatePassword ()

Summarize


Related articles: