在 PHP 中,可以使用 OpenSSL 扩展库进行加密和解密操作
首先确保已安装了 OpenSSL 扩展。大多数环境中默认已经安装。接下来,可以使用以下代码示例进行加密和解密:
<?php// 定义加密方法$cipher = "AES-256-CBC";// 定义加密所需的密钥和初始化向量(IV)$key = "your-32-character-key-here!"; // 密钥长度必须为32字节(256位)$iv = "your-16-character-iv!"; // IV长度必须为16字节(128位)// 要加密的数据$data = "This is a secret message.";// 加密数据$encrypted_data = openssl_encrypt($data, $cipher, $key, 0, $iv);echo "Encrypted data: " . $encrypted_data . PHP_EOL;// 解密数据$decrypted_data = openssl_decrypt($encrypted_data, $cipher, $key, 0, $iv);echo "Decrypted data: " . $decrypted_data . PHP_EOL;?>请注意,密钥和 IV 应该是适当的长度,并且应该保密。在实际应用中,建议使用更安全的密钥和 IV 生成方法,例如 openssl_random_pseudo_bytes()。
此外,加密和解密时使用的加密算法、密钥和 IV 必须相同,这样才能正确解密数据。




