Introduction to YII2 Encryption and decryption

Source: Internet
Author: User
Tags yii
This article mainly introduces about YII2 encryption and decryption of the introduction, has a certain reference value, now share to everyone, the need for friends can refer to





Related environment


    • OS and IDE MacOS 10.13.1 & PhpStorm2018.1.2

    • Software version PHP7.1.8 Yii2.0.14


In Yii2, the repository for managing cryptographic decryption is called security, and it exists as a yii2 component, so you can get and use it through Yii:: $app->security.



The security component source code location is as follows


vendor/yiisoft/yii2/base/security.php


Security component A total of 15 public methods related to cryptographic decryption (& encoding), let's first make a list.


    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


I think some of you have never seen, it's okay, we all go to understand.



Generaterandomstring



The reason to say generaterandomstring First is because it is most commonly used, at least I am.


Public Function generaterandomstring ($length = 32) {...}


Generates a random string, the parameter $length represents the length of the string, and the default is 32 bits. It is worth noting that the value of this string is range [a-za-z0-9_-].



Generatepasswordhash & ValidatePassword



Generatepasswordhash & ValidatePassword are often used to encrypt the user's password and verify that the password is correct, since the MD5 may have been collided, when we use YII2 to develop the application, The Generatepasswordhash function encrypts the password and becomes the preferred one, and it calls the crypt function.



General usage is as follows


// Use generatePasswordHash to encrypt the user's password, and $ hash is stored in the library
$ hash = Yii :: $ app-> getSecurity ()-> generatePasswordHash ($ password);

// verify password with validatePassword
if (Yii :: $ app-> getSecurity ()-> validatePassword ($ password, $ hash)) {
     // password is correct
} else {
     // wrong password
}


Generaterandomkey



Similar to generaterandomstring , generates a random string with the parameter length, which defaults to 32 bits, the difference being that Generaterandomkey generates not ASCII.



Simply say generaterandomstring is approximately equal to Base64_encode (generaterandomkey).



Encryptbypassword & Decryptbypassword



Encoding and decoding functions that encode data using a secret key and then decode the encoded data with this key.



Example


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


Note that the encoded data obtained by the above is not ASCII, and can be wrapped by Base64_encode and Base64_decode in the outer wrapper.



EncryptByKey & DecryptByKey



It is also a set of encoding and decoding functions that are faster than passwords. 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, such as the ID of the member we can pass, so that this information will be used together with $inputkey as the key to decrypt the encryption.



Hkdf



exports a key from a given input key using the standard HKDF algorithm. The Hash_hkdf method is used in php7+, which is less than PHP7 using the Hash_hmac method.



Pbkdf2



Use the standard PBKDF2 algorithm to export a key from a 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 do some tagging of the data, Hashdata and ValidateData is the combination of accomplishing this task.



The hashdata is used to prefix the raw data with data such as the following code


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


You see a group of characters in front of Hello, which varies with the original data. So we have a special anti-tamper tag for the data, and the next step is validatedata.



Note: The third parameter of Hashdata indicates whether the generated hash value is in the original binary format. If it isfalse, a lowercase hexadecimal number is generated.



validatedata The data prefix has been added to the detection, the following code


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


If the original string is returned, the validation passes, or false is returned.



The third parameter of the ValidateData function should be the same as the value when the data is generated using hashdata () . It indicates whether the hash value in the data is in binary format. If it isfalse, the hash value is composed only of lowercase hexadecimal digits. Hexadecimal digits are generated.



CompareString



String comparisons that prevent timing attacks are very simple to use.


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


The results are true, otherwise they are not equal.



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


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


The above comparison logic, two strings are from the first one to compare each other, found that the difference will immediately return false, then by calculating the speed of the return to know which is probably the beginning of the different, so that the film has been a frequent occurrence of the bit crack password scene.



Instead of using comparestring to compare two strings, the time consumption of the function is constant, regardless of whether the strings are equal, which can effectively prevent a sequential attack.



Masktoken && Unmasktoken



Masktoken used to conceal the real token and not to compress, the same token finally generated a different random token, in the Yii2 csrf function on the use of Masktoken, the principle is not complex, we look at the source code.


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


The purpose of the Unmasktoken is also clear, used to get tokens masked by Masktoken.



Next we look at an example code


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


Finally, we summarize the following


    • Encryption/decryption: EncryptByKey (), DecryptByKey (), Encryptbypassword (), and Decryptbypassword ();

    • Key derivation using the standard algorithm: PBKDF2 () and HKDF ();

    • Prevent data tampering: Hashdata () and ValidateData ();

    • Password verification: Generatepasswordhash () and ValidatePassword ()


The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.