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

高洛峰
Release: 2023-03-04 14:16:01
Original
1443 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template