In the modern internet environment, data security is critical. To protect sensitive information, developers often need to encrypt and decrypt data. PHP, as a popular server-side language, offers a variety of encryption functions and libraries that support multiple algorithms. This article explains how to implement data encryption and decryption in PHP with practical code examples.
Symmetric encryption is the most common method, also called shared key encryption. The same key is used for both encryption and decryption. PHP supports algorithms such as AES, DES, and 3DES. Here's an example using AES-256-CBC:
function encrypt($data, $key) { $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc')); $encrypted = openssl_encrypt($data, 'aes-256-cbc', $key, 0, $iv); return base64_encode($iv . $encrypted); } function decrypt($data, $key) { $data = base64_decode($data); $iv = substr($data, 0, openssl_cipher_iv_length('aes-256-cbc')); $encrypted = substr($data, openssl_cipher_iv_length('aes-256-cbc')); return openssl_decrypt($encrypted, 'aes-256-cbc', $key, 0, $iv); } $key = 'secret_key'; $data = 'sensitive_data'; $encryptedData = encrypt($data, $key); echo 'Encrypted data: ' . $encryptedData . PHP_EOL; $decryptedData = decrypt($encryptedData, $key); echo 'Decrypted data: ' . $decryptedData . PHP_EOL;
Explanation:
Asymmetric encryption uses a pair of keys: a public key for encryption and a private key for decryption. PHP supports algorithms such as RSA. Example:
function encrypt($data, $publicKey) { openssl_public_encrypt($data, $encrypted, $publicKey); return base64_encode($encrypted); } function decrypt($encryptedData, $privateKey) { openssl_private_decrypt(base64_decode($encryptedData), $decrypted, $privateKey); return $decrypted; } $publicKey = openssl_pkey_get_public('file://path/to/public_key.pem'); $privateKey = openssl_pkey_get_private('file://path/to/private_key.pem'); $data = 'sensitive_data'; $encryptedData = encrypt($data, $publicKey); echo 'Encrypted data: ' . $encryptedData . PHP_EOL; $decryptedData = decrypt($encryptedData, $privateKey); echo 'Decrypted data: ' . $decryptedData . PHP_EOL;
Explanation:
Hash functions map data of arbitrary length to a fixed-length hash, typically for integrity verification rather than encryption. PHP supports MD5, SHA1, SHA256, etc. Example:
$data = 'sensitive_data'; $hashedData = md5($data); echo 'Hashed data: ' . $hashedData . PHP_EOL;
Explanation:
This article introduced how to implement data encryption and decryption in PHP, covering symmetric encryption, asymmetric encryption, and hash functions, with full code examples. Using these methods, developers can effectively protect sensitive data during transmission and storage.