Using PHP Encryption Functions for Secure Data Transmission
This article explains how PHP's built-in encryption functions such as md5, sha1, base64_encode/decode, and openssl_encrypt/decrypt can be used to secure data transmission, provides code examples demonstrating AES‑128‑CBC encryption and decryption, and highlights their role in protecting sensitive information.
With the rapid development of the Internet, ensuring the security of data transmission has become crucial for e‑commerce, banking, and internal corporate communications.
PHP, a widely used server‑side scripting language, offers several built‑in functions for hashing and encoding data, including md5 , sha1 , base64_encode , base64_decode , openssl_encrypt and openssl_decrypt .
The md5 and sha1 functions generate hash values that can be stored instead of plain passwords, while base64_encode / base64_decode provide a reversible encoding method. The OpenSSL functions allow developers to choose an algorithm, mode and padding, enabling stronger encryption such as AES‑128‑CBC.
Below is a practical PHP example that encrypts and decrypts a string using the AES‑128‑CBC algorithm:
<code><?php
// 加密函数
function encrypt($data, $key) {
$encrypted = openssl_encrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
return base64_encode($encrypted);
}
// 解密函数
function decrypt($data, $key) {
$data = base64_decode($data);
return openssl_decrypt($data, 'AES-128-CBC', $key, OPENSSL_RAW_DATA, $iv);
}
// 加密数据
$data = "Hello World!";
$key = "MySecretKey";
$encrypted = encrypt($data, $key);
// 解密数据
$decrypted = decrypt($encrypted, $key);
echo "原始数据: " . $data . "\n";
echo "加密后的数据: " . $encrypted . "\n";
echo "解密后的数据: " . $decrypted . "\n";
?>
</code>The sample defines encrypt() that encrypts a string with AES‑128‑CBC using a key and IV, then returns a base64‑encoded ciphertext; decrypt() reverses the process. The script demonstrates encrypting and decrypting the string “Hello World!” and prints the original, encrypted and decrypted values.
By leveraging these PHP encryption functions, developers can protect data during transmission, making them essential for login, payment, and other sensitive operations.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.