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
- ##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 learn about them one by one.
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 & 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
generateRandomString
, generating a random string, the parameter is the length, the default is 32 bits, the difference isgenerateRandomKeyThe 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){}
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 solutiongeneratePasswordHash
.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 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 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')){ }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)); }
而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!

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP remains important in modern web development, especially in content management and e-commerce platforms. 1) PHP has a rich ecosystem and strong framework support, such as Laravel and Symfony. 2) Performance optimization can be achieved through OPcache and Nginx. 3) PHP8.0 introduces JIT compiler to improve performance. 4) Cloud-native applications are deployed through Docker and Kubernetes to improve flexibility and scalability.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment