Yii::$app->security->compareString("abc",'abc');
Introduction to yii2 encryption and decryption
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){...}
// 使用generatePasswordHash为用户的密码加密,$hash存储到库中 $hash = Yii::$app->getSecurity()->generatePasswordHash($password); // 使用validatePassword对密码进行验证 if(Yii::$app->getSecurity()->validatePassword($password, $hash)){ // 密码正确 }else{ // 密码错误 }
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){}
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
public function encryptByKey($data, $inputKey, $info = null){} public function decryptByKey($data, $inputKey, $info = null){}
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); // ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello
false
, lowercase hexadecimal numbers will be generated.validateData
$result = Yii::$app->security->validateData("ac28d602c767424d0c809edebf73828bed5ce99ce1556f4df8e223faeec60eddhello",'123456',false); // hello
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');
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.
Yii::$app->security->compareString("abc",'abc');
if($code == Yii::$app->request->get('code')){ }
而使用 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!

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

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
