Current Location: Home> Latest Articles> Complete PHP Guide for Encrypting Chinese Text: Using openssl_encrypt and openssl_decrypt

Complete PHP Guide for Encrypting Chinese Text: Using openssl_encrypt and openssl_decrypt

M66 2025-10-29

Overview of Chinese Text Encryption in PHP

In PHP, encrypting Chinese text primarily relies on the openssl extension. Using openssl_encrypt() and openssl_decrypt(), you can securely encrypt and decrypt data.

Installing the openssl Extension

First, ensure that the openssl extension is installed in your PHP environment. If it is not installed, use the following command:

pecl install openssl

Encrypting Chinese Text with openssl_encrypt()

The openssl_encrypt() function is used to encrypt data. The basic syntax is as follows:

string openssl_encrypt(string $data, string $cipher, string $key, int $options, string $iv)

Parameter Description

  • $data: The Chinese text to be encrypted
  • $cipher: Encryption algorithm, recommended AES-256-CBC
  • $key: Encryption key, must be 32 bytes long
  • $options: Encryption options, usually OPENSSL_RAW_DATA
  • $iv: Initialization vector, must be 16 bytes long

Example Code

$data = 'Chinese text';
$key = '32-byte long encryption key';
$iv = '16-byte long initialization vector';

$encrypted_data = openssl_encrypt($data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

Decrypting Data with openssl_decrypt()

The encrypted data can be decrypted using the openssl_decrypt() function. Its syntax is the same as the encryption function:

string openssl_decrypt(string $data, string $cipher, string $key, int $options, string $iv)

Decryption Example

$decrypted_data = openssl_decrypt($encrypted_data, 'AES-256-CBC', $key, OPENSSL_RAW_DATA, $iv);

Important Notes

  • The key and initialization vector used for encryption and decryption must be identical.
  • Ensure your encryption key is secure and not exposed.
  • Choose appropriate encryption algorithms and key lengths to meet security requirements.

Summary

By following these steps, you can securely encrypt and decrypt Chinese text in PHP. Using the openssl extension is simple, efficient, and sufficient for most project security needs.