Home Backend Development PHP Tutorial Summary of using PHP's openssl encryption extension (recommended)

Summary of using PHP's openssl encryption extension (recommended)

Dec 30, 2016 pm 01:58 PM

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加密
  ...
  )
Copy after login

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();  // 从证书导出私匙;
Copy after login

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 ] )
Copy after login

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(); // 使用公匙解密;
Copy after login

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 ] )
Copy after login

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,
  ...
)
Copy after login

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;
Copy after login

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

Video Face Swap

Video Face Swap

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

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)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1267
29
C# Tutorial
1239
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

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.

Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Explain secure password hashing in PHP (e.g., password_hash, password_verify). Why not use MD5 or SHA1? Apr 17, 2025 am 12:06 AM

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values ​​to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

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.

What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? What are HTTP request methods (GET, POST, PUT, DELETE, etc.) and when should each be used? Apr 09, 2025 am 12:09 AM

HTTP request methods include GET, POST, PUT and DELETE, which are used to obtain, submit, update and delete resources respectively. 1. The GET method is used to obtain resources and is suitable for read operations. 2. The POST method is used to submit data and is often used to create new resources. 3. The PUT method is used to update resources and is suitable for complete updates. 4. The DELETE method is used to delete resources and is suitable for deletion operations.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

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

Explain the difference between self::, parent::, and static:: in PHP OOP. Explain the difference between self::, parent::, and static:: in PHP OOP. Apr 09, 2025 am 12:04 AM

In PHPOOP, self:: refers to the current class, parent:: refers to the parent class, static:: is used for late static binding. 1.self:: is used for static method and constant calls, but does not support late static binding. 2.parent:: is used for subclasses to call parent class methods, and private methods cannot be accessed. 3.static:: supports late static binding, suitable for inheritance and polymorphism, but may affect the readability of the code.

How does PHP handle file uploads securely? How does PHP handle file uploads securely? Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

How does PHP type hinting work, including scalar types, return types, union types, and nullable types? How does PHP type hinting work, including scalar types, return types, union types, and nullable types? Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles