search
HomeBackend DevelopmentPHP TutorialSummary of using PHP's openssl encryption extension (recommended)

Introduction

In the history of the development of the Internet, security has always been a subject that developers attach great importance to. In order to achieve data transmission security, we need to ensure: data source (non-forged requests), data integrity ( has not been modified), data privacy (encrypted text, cannot be read directly), etc. Although there is already an HTTPS protocol implemented by the SSL/TLS protocol, it relies on the correct implementation of the browser on the client and is very inefficient. Therefore, general sensitive data (such as transaction payment information, etc.) still require us to use encryption methods. to manually encrypt.

Although it is not necessary for ordinary WEB developers to have an in-depth understanding of some underlying security-related technologies, it is necessary to learn the basics of encryption and use existing encryption-related tools. Due to work needs, I read some encryption-related articles and completed this article based on my own experience.

Encryption Basics

Before learning how to use encryption, we need to understand some basic knowledge related to encryption.

Encryption algorithms are generally divided into two types: symmetric encryption algorithms and asymmetric encryption algorithms.

Symmetric encryption

The symmetric encryption algorithm is that the sender and receiver of the message use the same key. The sender uses the key to encrypt the file, and the receiver uses the same key to decrypt and obtain the information. . Common symmetric encryption algorithms are: des/aes/3des.

The characteristics of symmetric encryption algorithms are: fast, the file size does not change much before and after encryption, but the storage of the key is a big problem, because the sender of the message If the key of either party is lost, the information transmission will become unsafe.

Asymmetric encryption

The opposite of symmetric encryption is asymmetric encryption. The core idea of ​​asymmetric encryption is to use a pair of relative keys, divided into public keys and private keys. The private key itself Keep it safe and make the public key public. The public key and the private key are a pair. If the public key is used to encrypt data, only the corresponding private key can be used to decrypt it; if the private key is used to encrypt the data, then only the corresponding public key can be used to decrypt it. Just use the recipient's public key to encrypt the data before sending it. Common asymmetric encryption algorithms include RSA/DSA:

Although asymmetric encryption does not have key storage problems, it requires a large amount of calculation and the encryption speed is very slow. Sometimes we need to block large pieces of data. encryption.

Digital signature

In order to ensure the integrity of the data, a hash value needs to be calculated through a hash function. This hash value is called a digital signature. Its characteristics are:

•No matter how big the original data is, the length of the result is the same;
•The input is the same, and the output is the same;
•Small changes to the input will make a big difference in the result. changes;
•The encryption process is irreversible, and the original data cannot be obtained through the hash value;

Common digital signature algorithms include md5, hash1 and other algorithms.

PHP’s openssl extension

The openssl extension uses the openssl encryption extension package, which encapsulates multiple PHP functions related to encryption and decryption, which greatly facilitates the encryption and decryption of data. Commonly used functions are:

Symmetric encryption related:

string openssl_encrypt (string $data, string $method, string $password)

where $data is to be encrypted Data, $method is the method to be used for encryption, $password is the key to be used, and the function returns the encrypted data;

The $method list can be obtained using openssl_get_cipher_methods(), we select one of them and use , the $method list is in the form:

Array(
  0 => aes-128-cbc,  // aes加密
  1 => des-ecb,    // des加密
  2 => des-ede3,   // 3des加密
  ...
  )

The decryption function is string openssl_encrypt (string $data, string $method, string $password)

Asymmetric encryption related:

openssl_get_publickey();openssl_pkey_get_public();   // 从证书导出公匙;
openssl_get_privatekey();openssl_pkey_get_private();  // 从证书导出私匙;

They all only need to pass in the certificate file (usually a .pem file);

openssl_public_encrypt(string $data , string &$crypted , mixed $key [, int $padding = OPENSSL\_PKCS1\_PADDING ] )

Use the public key to encrypt the data, where $data is the data to be encrypted; $crypted is a reference variable, the encrypted data will be put into this variable; $key is the public key data to be passed in; because when the encrypted data is grouped, it may not be exactly an integer multiple of the number of encryption bits, so $padding is required. The optional options of $padding are OPENSSL_PKCS1_PADDING, OPENSSL_NO_PADDING, which are PKCS1 padding or no padding respectively;

The opposite of this method is (the incoming parameters are consistent):

openssl_private_encrypt(); // 使用私匙加密;
openssl_private_decrypt(); // 使用私匙解密;
openssl_private_decrypt(); // 使用公匙解密;

There is also a signature And signature verification function:

bool openssl_sign ( string $data , string &$signature , mixed $priv_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )
int openssl_verify ( string $data , string $signature , mixed $pub_key_id [, mixed $signature_alg = OPENSSL_ALGO_SHA1 ] )

Signature function: $data is the data to be signed; $signature is the reference variable of the signature result; $priv_key_id is the private key used for the signature; $signature_alg is the algorithm to be used for the signature , the algorithm list can be obtained using openssl_get_md_methods (), in the form:

array(
  0 => MD5,
  1 => SHA1,
  2 => SHA256,
  ...
)

Signature verification function: It is opposite to the signature function, except that it needs to pass in the public key corresponding to the private key; the result is the signature verification result , 1 means success, 0 means failure, -1 means error;

Encryption example

The following is a small example of asymmetric encryption:

// 获取公匙
$pub_key = openssl_get_publickey('test.pem');
 
$encrypted = '';
// 对数据分块加密
for ($offset = 0, $length = strlen($raw_msg); $offset < $length; $offset += $key_size){  
  $encryptedBlock = &#39;&#39;;
  $data = substr($raw_msg, $offset, $key_size)
  if (!openssl_public_encrypt($data, $encryptedBlock, $pub_key, OPENSSL_PKCS1_PADDING)){
    return &#39;&#39;;
  } else {
    $encrypted .= $encryptedBlock;
 }
 return $encrypted;

And symmetric encryption It's very simple, just use the ssl_encrypt() function;

Of course, some interfaces may have different requirements for encryption methods, such as different padding, encryption block size, etc., which require the user to adjusted.

Because we are processing data on top of the HTTP protocol, after the data encryption is completed, it can be sent directly. There is no need to consider the underlying transmission. Using cURL or SOAP extension methods, you can directly request the interface. .

Conclusion

Cryptography is a very advanced subject with difficult theories and many concepts. As a WEB developer, although we do not need to study its underlying implementation, learning to use encapsulated methods is very beneficial to our development. Even understanding its basic implementation can help you gain a new understanding of algorithms and so on.

The above summary of the use of PHP's openssl encryption extension (recommended) is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more PHP openssl encryption extension usage summary (recommended), please pay attention to the PHP Chinese website!

Statement
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
How do you modify data stored in a PHP session?How do you modify data stored in a PHP session?Apr 27, 2025 am 12:23 AM

TomodifydatainaPHPsession,startthesessionwithsession_start(),thenuse$_SESSIONtoset,modify,orremovevariables.1)Startthesession.2)Setormodifysessionvariablesusing$_SESSION.3)Removevariableswithunset().4)Clearallvariableswithsession_unset().5)Destroythe

Give an example of storing an array in a PHP session.Give an example of storing an array in a PHP session.Apr 27, 2025 am 12:20 AM

Arrays can be stored in PHP sessions. 1. Start the session and use session_start(). 2. Create an array and store it in $_SESSION. 3. Retrieve the array through $_SESSION. 4. Optimize session data to improve performance.

How does garbage collection work for PHP sessions?How does garbage collection work for PHP sessions?Apr 27, 2025 am 12:19 AM

PHP session garbage collection is triggered through a probability mechanism to clean up expired session data. 1) Set the trigger probability and session life cycle in the configuration file; 2) You can use cron tasks to optimize high-load applications; 3) You need to balance the garbage collection frequency and performance to avoid data loss.

How can you trace session activity in PHP?How can you trace session activity in PHP?Apr 27, 2025 am 12:10 AM

Tracking user session activities in PHP is implemented through session management. 1) Use session_start() to start the session. 2) Store and access data through the $_SESSION array. 3) Call session_destroy() to end the session. Session tracking is used for user behavior analysis, security monitoring, and performance optimization.

How can you use a database to store PHP session data?How can you use a database to store PHP session data?Apr 27, 2025 am 12:02 AM

Using databases to store PHP session data can improve performance and scalability. 1) Configure MySQL to store session data: Set up the session processor in php.ini or PHP code. 2) Implement custom session processor: define open, close, read, write and other functions to interact with the database. 3) Optimization and best practices: Use indexing, caching, data compression and distributed storage to improve performance.

Explain the concept of a PHP session in simple terms.Explain the concept of a PHP session in simple terms.Apr 26, 2025 am 12:09 AM

PHPsessionstrackuserdataacrossmultiplepagerequestsusingauniqueIDstoredinacookie.Here'showtomanagethemeffectively:1)Startasessionwithsession_start()andstoredatain$_SESSION.2)RegeneratethesessionIDafterloginwithsession_regenerate_id(true)topreventsessi

How do you loop through all the values stored in a PHP session?How do you loop through all the values stored in a PHP session?Apr 26, 2025 am 12:06 AM

In PHP, iterating through session data can be achieved through the following steps: 1. Start the session using session_start(). 2. Iterate through foreach loop through all key-value pairs in the $_SESSION array. 3. When processing complex data structures, use is_array() or is_object() functions and use print_r() to output detailed information. 4. When optimizing traversal, paging can be used to avoid processing large amounts of data at one time. This will help you manage and use PHP session data more efficiently in your actual project.

Explain how to use sessions for user authentication.Explain how to use sessions for user authentication.Apr 26, 2025 am 12:04 AM

The session realizes user authentication through the server-side state management mechanism. 1) Session creation and generation of unique IDs, 2) IDs are passed through cookies, 3) Server stores and accesses session data through IDs, 4) User authentication and status management are realized, improving application security and user experience.

See all articles

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

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.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function