php实现对称加密
PHP 实现对称加密的方法
对称加密使用相同的密钥进行加密和解密,以下是几种常见的实现方式:
使用 OpenSSL 扩展
PHP 的 OpenSSL 扩展提供了强大的加密功能,支持 AES 等对称加密算法。
$plaintext = "敏感数据";
$method = "AES-256-CBC";
$key = openssl_random_pseudo_bytes(32); // 生成随机密钥
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
// 加密
$ciphertext = openssl_encrypt($plaintext, $method, $key, OPENSSL_RAW_DATA, $iv);
$encrypted = base64_encode($iv.$ciphertext);
// 解密
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, openssl_cipher_iv_length($method));
$ciphertext = substr($decoded, openssl_cipher_iv_length($method));
$plaintext = openssl_decrypt($ciphertext, $method, $key, OPENSSL_RAW_DATA, $iv);
使用 Sodium 扩展
PHP 7.2+ 内置的 Sodium 扩展提供了现代加密算法,更安全且易于使用。
$plaintext = "敏感数据";
$key = sodium_crypto_secretbox_keygen(); // 生成随机密钥
// 加密
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = sodium_crypto_secretbox($plaintext, $nonce, $key);
// 解密
$decrypted = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
使用 Mcrypt 扩展(已废弃)
虽然 Mcrypt 扩展在 PHP 7.1 中已被移除,但在旧版本中仍可使用:
$plaintext = "敏感数据";
$key = "32字节长度的密钥..."; // 必须准确长度
$iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));
// 加密
$ciphertext = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $key, $plaintext, MCRYPT_MODE_CBC, $iv);
// 解密
$plaintext = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $ciphertext, MCRYPT_MODE_CBC, $iv);
注意事项
- 始终使用安全的随机数生成器(如
random_bytes()或openssl_random_pseudo_bytes())生成密钥和 IV - 对于 AES,密钥长度必须准确(AES-128=16字节,AES-256=32字节)
- 不要硬编码密钥,应安全存储
- 考虑使用 HMAC 进行数据完整性验证
- OpenSSL 和 Sodium 是推荐选择,Mcrypt 已过时
最佳实践
存储加密数据时,建议将 IV/nonce 与密文一起存储(通常前置),使用时再分离。对于传输,可以使用 base64 编码:
// 组合 IV 和密文
$encrypted = base64_encode($iv.$ciphertext);
// 分离 IV 和密文
$decoded = base64_decode($encrypted);
$iv = substr($decoded, 0, $ivLength);
$ciphertext = substr($decoded, $ivLength);






