Home Backend Development PHP Tutorial How to handle data encryption and decryption when implementing API in PHP

How to handle data encryption and decryption when implementing API in PHP

Jun 17, 2023 pm 03:40 PM
Decrypt encryption api processing

With the continuous development of the Internet, the application scope of API (Application Programming Interface) is becoming more and more extensive, and data interactions between various systems are becoming more and more frequent. For the transmission of sensitive data, data encryption and decryption are essential steps. This article will introduce how to handle data encryption and decryption when implementing API based on PHP.

1. Why data encryption is necessary

Data encryption refers to converting original plaintext into ciphertext according to a certain algorithm, so that people who have not obtained the corresponding key cannot interpret it, thereby achieving Confidentiality of data. In API development, the main reasons for data encryption are the following two points:

  1. Data security

When the API is open to third parties, due to the Transmission does not guarantee that it will be carried out in a private communication environment, so the security and authenticity of the data can be ensured through encryption to avoid data being stolen or tampered with during the transmission process.

  1. Legality Verification

Data encryption can ensure the legality of data transmission through identity verification, signature, etc. During the API request sending process, the request parameters are encrypted with irreversible algorithms to ensure the legitimacy of the request and prevent illegal tampering or forgery of the request data.

2. PHP implements data encryption

  1. Symmetric encryption algorithm

Symmetric encryption algorithm means that the key used for encryption and decryption is the same , you only need to pass the key as a parameter to complete the encryption and decryption operations. Symmetric encryption algorithms commonly used in API development include DES, 3DES, AES, etc.

Taking the AES encryption algorithm as an example, PHP provides functions such as openssl_encrypt() and openssl_decrypt() to implement symmetric encryption operations. The usage method is as follows:

//AES加密
function aesEncrypt($data, $key) {
    $iv_len = openssl_cipher_iv_length('AES-128-CBC');
    $iv = openssl_random_pseudo_bytes($iv_len);
    $encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
    $result = base64_encode($iv . $encrypted);
    return $result;
}
//AES解密
function aesDecrypt($data, $key) {
    $data = base64_decode($data);
    $iv_len = openssl_cipher_iv_length('AES-128-CBC');
    $iv = substr($data, 0, $iv_len);
    $encrypted = substr($data, $iv_len);
    $decrypted = openssl_decrypt($encrypted, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
    return $decrypted;
}
Copy after login

Among them, $data is the data to be encrypted, and $key is the key. During the encryption process, obtain the length of the IV vector required by the encryption algorithm by calling openssl_cipher_iv_length(), call openssl_random_pseudo_bytes() to generate a random IV vector, and then call the openssl_encrypt() function to perform the encryption operation. In the decryption process, the ciphertext is first restored to binary data through the base64_decode() function, then the IV vector and encrypted data are extracted respectively, and the openssl_decrypt() function is called to perform the decryption operation.

  1. Asymmetric encryption algorithm

Asymmetric encryption algorithm means that the keys used for encryption and decryption are different. Generally, the public key is made public and used to encrypt data. It is then decrypted by the private key on the server side. In API development, common asymmetric encryption algorithms include RSA, DSA, etc.

Taking the RSA encryption algorithm as an example, PHP provides functions such as openssl_public_encrypt and openssl_private_decrypt to implement asymmetric encryption operations. The usage method is as follows:

//RSA加密
function rsaEncrypt($data,$public_key) {
    $encrypted = '';
    openssl_public_encrypt($data,$encrypted,$public_key,OPENSSL_PKCS1_PADDING);
    $encrypted = base64_encode($encrypted);
    return $encrypted;
}
//RSA解密
function rsaDecrypt($data,$private_key) {
    $decrypted = '';
    openssl_private_decrypt(base64_decode($data),$decrypted,$private_key,OPENSSL_PKCS1_PADDING);
    return $decrypted;
}
Copy after login

Among them, $data is the data to be encrypted, and $public_key is the public key. During the encryption process, the data is encrypted by calling the openssl_public_encrypt() function, and then the encrypted data is encoded by the base64_encode() function. During the decryption process, the encrypted data is decrypted by calling the openssl_private_decrypt() function, and then the decrypted data is returned.

3. PHP implements data signature

The data signature in the API is verified for legality by hashing the parameters. For API request parameters, the server needs to perform data signatures to ensure the integrity and authenticity of data transmission.

Commonly used hash algorithms include HMAC, SHA1, MD5, etc. Taking HMAC as an example, data signature can be easily implemented using PHP's built-in hash_hmac() function. The usage is as follows:

//HMAC签名
function hmacSign($data, $secret) {
    $signed_data = hash_hmac('sha256', $data, $secret, false);
    return $signed_data;
}
Copy after login

Among them, $data is the data to be signed, and $secret is the signing key. Call the hash_hmac() function to hash-encrypt the data and return the signed data.

4. Data Encryption and Decryption Example

Next, we will comprehensively apply the above data encryption and signature methods to demonstrate how to use PHP to complete the encryption and decryption process of API request parameters.

//数据加密
$data = [
    'user_id' => 12345,
    'user_name' => 'test',
    'timestamp' => time(),
];
$json_data = json_encode($data);
$encrypted_data = aesEncrypt($json_data, $encrypt_key);

//数据签名
$signature_data = $encrypted_data . $secret_key;
$signature = hmacSign($signature_data, $hmac_key);

//API请求构造
$params = [
    'data' => $encrypted_data,
    'signature'=> $signature,
];
$request_url = 'http://api.example.com' . '?'. http_build_query($params);

//API响应解析
$response_data = file_get_contents($request_url);
$response_data = json_decode($response_data, true);

//数据解密
$encrypted_data = $response_data['data'];
$signature_data = $encrypted_data . $secret_key;
$signature = $response_data['signature'];
if(hmacSign($signature_data, $hmac_key) === $signature) {
    $json_data = aesDecrypt($encrypted_data, $encrypt_key);
    $response = json_decode($json_data, true);
    //TODO:处理API响应数据
}
else {
    //TODO:处理签名不合法的情况
}
Copy after login

In the above code, the aesEncrypt() function is first used to symmetrically encrypt the request parameters, and then the hmacSign() function is used to hash the encrypted data to generate signed request parameters. After the server receives the request, it verifies whether the signature is legal by hashing the signature data, and then uses the aesDecrypt() function to decrypt the encrypted data to obtain the original request parameters.

In the actual application process, it is necessary to ensure that encryption keys, signature keys and other information cannot be leaked to ensure the security of API data. At the same time, appropriate encryption and signature algorithms need to be selected based on system usage requirements to meet system performance and security requirements.

The above is the detailed content of How to handle data encryption and decryption when implementing API in PHP. 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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months 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)

Revealing the causes of HTTP status code 460 Revealing the causes of HTTP status code 460 Feb 19, 2024 pm 08:30 PM

Decrypting HTTP status code 460: Why does this error occur? Introduction: In daily network use, we often encounter various error prompts, including HTTP status codes. These status codes are a mechanism defined by the HTTP protocol to indicate the processing of a request. Among these status codes, there is a relatively rare error code, namely 460. This article will delve into this error code and explain why this error occurs. Definition of HTTP status code 460: First, we need to understand the basics of HTTP status code

How to set up encryption of photo album on Apple mobile phone How to set up encryption of photo album on Apple mobile phone Mar 02, 2024 pm 05:31 PM

In Apple mobile phones, users can encrypt photo albums according to their own needs. Some users don't know how to set it up. You can add the pictures that need to be encrypted to the memo, and then lock the memo. Next, the editor will introduce the method of setting up the encryption of mobile photo albums for users. Interested users, come and take a look! Apple mobile phone tutorial How to set up iPhone photo album encryption A: After adding the pictures that need to be encrypted to the memo, go to lock the memo for detailed introduction: 1. Enter the photo album, select the picture that needs to be encrypted, and then click [Add to] below. 2. Select [Add to Notes]. 3. Enter the memo, find the memo you just created, enter it, and click the [Send] icon in the upper right corner. 4. Click [Lock Device] below

How to set up word decryption How to set up word decryption Mar 20, 2024 pm 04:36 PM

In today's work environment, everyone's awareness of confidentiality is getting stronger and stronger, and encryption operations are often performed to protect files when using software. Especially for key documents, the awareness of confidentiality should be increased, and the security of documents should be given top priority at all times. So I don’t know how well everyone understands word decryption. How to operate it specifically? Today we will actually show you the process of word decryption through the explanation below. Friends who need to learn word decryption knowledge should not miss today's course. A decryption operation is first required to protect the file, which means that the file is processed as a protective document. After doing this to a file, a prompt pops up when you open the file again. The way to decrypt the file is to enter the password, so you can directly

How to set a password for folder encryption without compression How to set a password for folder encryption without compression Feb 20, 2024 pm 03:27 PM

Folder encryption is a common data protection method that encrypts the contents of a folder so that only those who have the decryption password can access the files. When encrypting a folder, there are some common ways to set a password without compressing the file. First, we can use the encryption function that comes with the operating system to set a folder password. For Windows users, you can set it up by following the following steps: Select the folder to be encrypted, right-click the folder, and select "Properties"

How to encrypt the compressed package in winrar-winrar encrypted compressed package method How to encrypt the compressed package in winrar-winrar encrypted compressed package method Mar 23, 2024 pm 12:10 PM

The editor will introduce to you three methods of encryption and compression: Method 1: Encryption The simplest encryption method is to enter the password you want to set when encrypting the file, and the encryption and compression are completed. Method 2: Automatic encryption Ordinary encryption method requires us to enter a password when encrypting each file. If you want to encrypt a large number of compressed packages and the passwords are the same, then we can set automatic encryption in WinRAR, and then just When compressing files normally, WinRAR will add a password to each compressed package. The method is as follows: Open WinRAR, click Options-Settings in the setting interface, switch to [Compression], click Create Default Configuration-Set Password Enter the password we want to set here, click OK to complete the setting, we only need to correct

How to decrypt the encrypted computer version of EZVIZ Cloud Video? -EZVIZ Cloud Video PC version exits full screen? How to decrypt the encrypted computer version of EZVIZ Cloud Video? -EZVIZ Cloud Video PC version exits full screen? Mar 18, 2024 pm 12:25 PM

How to de-encrypt videos on EZVIZ Cloud: There are many ways to de-encrypt videos on EZVIZ Cloud, one of which is by using the EZVIZ Cloud Mobile App. Users only need to enter the device list, select the camera to be decrypted and enter the device details page. On the device details page, find the "Settings" option, and then select "Video Encryption" to make relevant settings. In the video encryption settings interface, you can choose the option to turn off video encryption, and save the settings to complete the decryption operation. This simple step allows users to easily decrypt videos and improves the convenience of using the camera. If you use the computer client of EZVIZ Cloud, you can also cancel video encryption through similar steps. Just log in and select the corresponding camera, enter the device details interface, and then look for video addition in the settings.

Decrypting the tricks added by the PyCharm interpreter Decrypting the tricks added by the PyCharm interpreter Feb 21, 2024 pm 03:33 PM

Decrypting the tricks added by the PyCharm interpreter PyCharm is the integrated development environment (IDE) preferred by many Python developers, and it provides many powerful features to improve development efficiency. Among them, the setting of the interpreter is an important part of PyCharm. Correctly setting the interpreter can help developers run the code smoothly and debug the program. This article will introduce some techniques for decrypting the PyCharm interpreter additions, and combine it with specific code examples to show how to correctly configure the interpreter. Adding and selecting interpreters in Py

Analog, a new project by crypto veterans: raised $16 million, with airdrop expected Analog, a new project by crypto veterans: raised $16 million, with airdrop expected Feb 22, 2024 pm 04:50 PM

Original author: Meteor, ChainCatcher Original editor: Marco, ChainCatcher Recently, the full-chain interoperability protocol Analog has entered the public eye with the disclosure of US$16 million in financing. Investment institutions include TribeCapital, NGCVentures, Wintermute, GSR, NEAR, OrangeDAO, and Mike Novogratz’s Alternative asset management companies Samara Asset Group, Balaji Srinivasan, etc. At the end of 2023, Analog caused some excitement in the industry. They released information on the open testnet registration event on the X platform.

See all articles