php加密实现
PHP 加密方法
PHP 提供了多种加密方式,适用于不同场景,如密码存储、数据传输等。以下是常见的加密实现方法:
密码哈希(推荐用于用户密码)
使用 password_hash() 和 password_verify() 函数,这是目前最安全的密码存储方式:
// 创建密码哈希
$password = "user_password";
$hash = password_hash($password, PASSWORD_DEFAULT);
// 验证密码
if (password_verify($password, $hash)) {
echo "密码正确";
} else {
echo "密码错误";
}
对称加密(AES)
使用 OpenSSL 扩展进行 AES 加密:
$method = 'AES-256-CBC';
$key = openssl_random_pseudo_bytes(32); // 256位密钥
$iv = openssl_random_pseudo_bytes(16); // 初始向量
// 加密
$data = "敏感数据";
$encrypted = openssl_encrypt($data, $method, $key, 0, $iv);
// 解密
$decrypted = openssl_decrypt($encrypted, $method, $key, 0, $iv);
非对称加密(RSA)
生成密钥对并加解密:
// 生成密钥对
$config = array(
"private_key_bits" => 2048,
);
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$publicKey = openssl_pkey_get_details($res)["key"];
// 加密
openssl_public_encrypt("原始数据", $encrypted, $publicKey);
// 解密
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
HMAC 签名
用于数据完整性验证:

$key = 'secret_key';
$data = "需要签名的数据";
$hmac = hash_hmac('sha256', $data, $key);
安全注意事项
- 密码存储必须使用
password_hash(),切勿使用 md5 或 sha1 - 对称加密需要安全地存储密钥
- 非对称加密的私钥必须严格保护
- 加密算法参数应使用当前推荐的安全配置
性能考虑
- 密码哈希应适当设置成本参数(如
PASSWORD_BCRYPT的 cost) - 大数据量加密考虑使用流式加密
- 频繁加密操作可能需要缓存机制






