Table of Contents
What is symmetric and asymmetric encryption" >What is symmetric and asymmetric encryption
What should we do for system security? " >What should we do for system security?
OpenSSL Extended Symmetric Encryption" >OpenSSL Extended Symmetric Encryption
Symmetric encryption/decryption implementation
Symmetric encryption algorithm query
Summary" >Summary
Home Backend Development PHP Problem How PHP uses symmetric encryption in OpenSSL encryption

How PHP uses symmetric encryption in OpenSSL encryption

May 31, 2021 am 09:28 AM
php

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.

1

2

[root@localhost ~]# openssl version

OpenSSL 1.1.1 FIPS  11 Sep 2018

Copy after login

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

Symmetric encryption/decryption implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

$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

Copy after login

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.

1

2

3

4

5

6

7

$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;

// 测试对称加密

Copy after login

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

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

//     ……

// )

Copy after login

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:

1

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

Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

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

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

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

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

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

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

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

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

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,

See all articles