Home  >  Article  >  Backend Development  >  How PHP uses symmetric encryption in OpenSSL encryption

How PHP uses symmetric encryption in OpenSSL encryption

醉折花枝作酒筹
醉折花枝作酒筹forward
2021-05-31 09:28:432665browse

This article will introduce to you how PHP uses symmetric encryption in OpenSSL encryption. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

How PHP uses symmetric encryption in OpenSSL encryption

#We have learned a lot about encryption extensions in PHP. Starting today, what we are going to learn is the key point, which is the use of OpenSSL encryption extension. Why is it said to be the most important point? First, OpenSSL is currently the de facto standard for data encryption in PHP and even in the entire development circle. Encryption including HTTPS/SSL is its practical application. Second, OpenSSL provides symmetric and asymmetric encryption forms, which is what we daily The two most common encryption methods in , these are what we need to master.

So, is it any different from Hash class encryption? Hash type encryption is one-way irreversible encryption. The encrypted content is a hexadecimal Hash string. We can only use the rainbow table to reverse the plaintext content, so as long as we add a salt value or multiple sets of two-layer encryption, It is very difficult to reverse engineer it. Therefore, Hash encryption is usually used to save user passwords. Even if the database leaks the user password, it is still safe. OpenSSL's type of symmetric/asymmetric encryption can perform forward encryption and reverse decryption through a certain keyword or certificate. The original text

is available. Now let’s talk about symmetric and asymmetric encryption in detail.

What is symmetric and asymmetric encryption

Symmetric encryption usually encrypts the original text through a key. In other words, whether it is the server, the client or any other peer, when the two ends communicate, the encrypted content they transmit must use the same key for encryption/decryption operations. Both ends must save such a key at the same time. I guess everyone has also thought of it. Now whether it is web development or app development, the code can be decompiled and the source code can be viewed. If symmetric encryption is used, the key can be easily obtained. However, the advantage of symmetric encryption is that it is very fast and does not consume resources.

Asymmetric encryption holds different keys at both ends. Just like the most common https certificates we see, they have two concepts: public key and private key. Generally, we will use the public key for encryption, and then use the private key for decryption. Usually the public key is made public and sent to the other party, while the private key is kept here. That is to say, when the other party sends us data, it uses the public key we gave it to encrypt the data. The data is very safe during the transmission process, because no one else has the private key to decrypt the data until we After receiving the data, you use your own private key to decrypt it and get the original data. Since the key contents on both sides are not the same, asymmetric encryption is much more secure than symmetric encryption. Although the algorithm and complexity of asymmetric encryption are several levels higher than that of symmetric encryption, compared with the advantages of symmetric encryption, speed and performance have become its bottlenecks in asymmetric encryption, especially when the amount of data is large. in the case of. In addition, the mathematical principle of asymmetric encryption is that it is difficult to decompose large numbers, that is, the larger the number, the more difficult it is to factorize. If an algorithm can crack this problem in a short time, then congratulations, it is the basis of modern encryption algorithms. The ceiling was broken by you.

Commonly used algorithms for symmetric encryption include: AES, DES, 3DES, IDEA, RC2, RC5, etc. The more commonly used algorithms are AES and DES.

Commonly used algorithms for asymmetric encryption include: RSA, Elgamal, ECC, etc. RSA is very commonly used and common. SSL and some certificate algorithms are based on RSA.

What should we do for system security?

So, do we have a compromise way to use these two encryption capabilities? Of course there is, and it is also a very classic technology: digital envelopes.

In fact, the meaning is very simple, which is to take advantage of the respective advantages of these two encryption methods. Asymmetric encryption has high security, but slow speed, and the larger the amount of data, the slower the speed. Then we use it to encrypt the key of symmetric encryption. Usually this key is not very large. Then the actual data entity uses this symmetrically encrypted key to perform symmetric encryption to improve speed. In this way, when we send it to the client, it includes two contents, one is the key encrypted using asymmetric encryption, and the other is the data content encrypted using symmetric encryption. After the client gets the information, it first uses the asymmetric encryption key to decode the symmetric encryption key, and then uses this key to decrypt the final data content. Are you confused? Let’s take a look at it through a picture, maybe everyone will understand it at a glance.

How PHP uses symmetric encryption in OpenSSL encryption

There is no need to explain the public key and private key. The session key is the key of our symmetric encryption algorithm. Combined with the above explanation of the digital envelope transmission process, everyone should be able to understand it.

OpenSSL Extended Symmetric Encryption

Okay, after introducing so much theoretical knowledge, let’s get back to the topic. How do we implement symmetric and asymmetric encryption in PHP? Woolen cloth? It's very simple, just use the OpenSSL extension. This extension is also released with the PHP source code. Just add --with-openssl when compiling and installing. Of course, it also requires OpenSSL software to be installed in the system environment. It is basically already available in various operating systems. If not, just install it yourself. The simplest way is to see if there is an openssl command on the operating system command line to see if OpenSSL related software is installed on the current system.

[root@localhost ~]# openssl version
OpenSSL 1.1.1 FIPS  11 Sep 2018

Today, we mainly study the relatively simple functions related to symmetric encryption.

Symmetric encryption/decryption implementation

$data = '测试对称加密';
$key = '加密用的key';
$algorithm =  'DES-EDE-CFB';


$ivlen = openssl_cipher_iv_length($algorithm);
$iv = openssl_random_pseudo_bytes($ivlen);


$password = openssl_encrypt($data, $algorithm, $key, 0, $iv);
echo $password, PHP_EOL;
// 4PvOc75QkIJ184/RULdOTeO8

echo openssl_decrypt($password, $algorithm, $key, 0, $iv), PHP_EOL;
// 测试对称加密

// Warning: openssl_encrypt(): Using an empty Initialization Vector (iv) is potentially insecure and not recommended

openssl_encrypt() is to encrypt data. It requires three parameters: original text, algorithm and key. The latter parameters are optional, but it is recommended now. To define the iv (vector) parameter, so if there is no iv parameter, a warning message will be reported. We use openssl_cipher_iv_length() to get the iv length required by the current algorithm, and then use the openssl_random_pseudo_bytes() function to generate a random iv content that matches the length of the algorithm.

The 0 parameter in the middle is the bitwise OR value of the specified tag. It has two optional constants: OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING. If set to OPENSSL_RAW_DATA, the encrypted data will be returned as is (binary garbled content). If set to OPENSSL_ZERO_PADDING, the encrypted data will be returned as the content after base64.

openssl_decrypt() is used to decrypt data. The required parameters are basically the same as the encryption function, except that the original data is replaced by encrypted data.

In symmetric encryption, we also have an AEAD cipher mode (GCM or CCM). When using this mode algorithm, we need one more parameter.

$algorithm =  'aes-128-gcm';
$password = openssl_encrypt($data, $algorithm, $key, 0, $iv, $tags);
echo $password, PHP_EOL;
// dPYsR+sdP56rQ99CNxciah+N

echo openssl_decrypt($password, $algorithm, $key, 0, $iv, $tags), PHP_EOL;
// 测试对称加密

This $tags is a reference type parameter, that is, it will be assigned to this variable after encryption. The same verification tag is also required during decryption.

From the perspective of the encryption and decryption process, if we want to save this information in the database, or when transmitting and decrypting, we must at least save or transmit these fields, the iv used for encryption, and the iv used for encryption. algorithm, and the verification tag used for encryption in AEAD mode, otherwise the data cannot be decrypted.

Symmetric encryption algorithm query

print_r(openssl_get_cipher_methods());

// Array
// (
//     [0] => AES-128-CBC
//     [1] => AES-128-CBC-HMAC-SHA1
//     [2] => AES-128-CFB
//     [3] => AES-128-CFB1
//     [4] => AES-128-CFB8
//     [5] => AES-128-CTR
//     [6] => AES-128-ECB
//     [7] => AES-128-OFB
//     [8] => AES-128-XTS
//     [9] => AES-192-CBC
//     [10] => AES-192-CFB
//     [11] => AES-192-CFB1
//     [12] => AES-192-CFB8
//     ……
// )

The algorithm selected in the above encryption/decryption test is found from this function. This function displays a list of all supported algorithms in the current environment.

Summary

The content of this article contains a lot of theoretical knowledge, and everyone still needs to digest it. Using OpenSSL to implement the encryption/decryption function is actually relatively simple. After all, everything has been encapsulated for us. We only need to call the function according to the documentation. Learning still requires combining theory with practice. Of course, the more important thing is to do it yourself!

Test code:

https://github.com/zhangyue0503/dev-blog/blob/master/php/202007/source/PHP%E7%9A%84OpenSSL%E5%8A%A0%E5%AF%86%E6%89%A9%E5%B1%95%E5%AD%A6%E4%B9%A0%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86.php

Recommended learning: php video tutorial

The above is the detailed content of How PHP uses symmetric encryption in OpenSSL encryption. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete