PHP 加密方式全解析
在 Web 开发中,数据加密是保护敏感信息的关键环节。PHP 提供了多种加密函数和扩展,适用于不同场景。以下是 PHP 中常用加密方式的总结:
专门用于密码存储,是最推荐的密码处理方式
$password = 'user_password';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($password, $hashedPassword)) {
echo "密码正确";
} else {
echo "密码错误";
}
if (password_needs_rehash($hashedPassword, PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
}
使用相同密钥进行加密和解密,适合加密大量数据
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($encrypted . '::' . $iv);
}
function decrypt($data, $key) {
list($encrypted_data, $iv) = explode('::', base64_decode($data), 2);
return openssl_decrypt($encrypted_data, 'aes-256-cbc', $key, 0, $iv);
}
$key = 'your-256-bit-secret-key-here';
$original = '敏感数据';
$encrypted = encrypt($original, $key);
$decrypted = decrypt($encrypted, $key);
使用公钥加密、私钥解密,适合密钥交换和数字签名
$config = [
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
];
$res = openssl_pkey_new($config);
openssl_pkey_export($res, $privateKey);
$publicKey = openssl_pkey_get_details($res)['key'];
$data = '需要加密的数据';
openssl_public_encrypt($data, $encrypted, $publicKey);
$encryptedData = base64_encode($encrypted);
openssl_private_decrypt(base64_decode($encryptedData), $decrypted, $privateKey);
单向加密,适用于数据完整性校验
$string = '需要哈希的数据';
$hash = hash('sha256', $string);
$salt = random_bytes(16);
$hashWithSalt = hash('sha256', $string . $salt);
$key = 'secret_key';
$hmac = hash_hmac('sha256', $string, $key);
结合数据库本身的加密功能,如 MySQL 的 AES_ENCRYPT () 和 AES_DECRYPT ()
- 永远不要自己实现加密算法,使用经过验证的库
- 密码必须使用 password_hash () 而非普通哈希
- 密钥管理至关重要,不要硬编码在代码中
- 敏感数据传输必须使用 HTTPS
- 根据数据敏感度选择合适的加密强度
- 定期轮换密钥和凭证
选择合适的加密方式取决于具体需求:密码存储用 password_hash,传输数据用 SSL/TLS,存储敏感数据用 AES 等对称加密,密钥交换用非对称加密。
发布时间 : 2025-09-08,阅读量:23
本文链接:
https://upwqy.com/details/998.html