php怎么实现加密
PHP 加密方法
PHP 提供了多种加密方式,包括哈希加密、对称加密和非对称加密。以下是常见的加密实现方法。
哈希加密
哈希加密是单向加密,常用于密码存储。PHP 内置了 password_hash 和 password_verify 函数。
// 生成哈希
$password = 'user_password';
$hashedPassword = password_hash($password, PASSWORD_DEFAULT);
// 验证哈希
if (password_verify($password, $hashedPassword)) {
echo '密码匹配';
} else {
echo '密码不匹配';
}
对称加密
对称加密使用相同的密钥进行加密和解密,常见算法为 AES-256-CBC。
// 加密
$data = '敏感数据';
$key = 'your_secret_key';
$iv = openssl_random_pseudo_bytes(16);
$encrypted = openssl_encrypt($data, 'AES-256-CBC', $key, 0, $iv);
// 解密
$decrypted = openssl_decrypt($encrypted, 'AES-256-CBC', $key, 0, $iv);
非对称加密
非对称加密使用公钥和私钥,常见算法为 RSA。
// 生成密钥对
$config = [
"digest_alg" => "sha512",
"private_key_bits" => 4096,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
];
$keyPair = openssl_pkey_new($config);
openssl_pkey_export($keyPair, $privateKey);
$publicKey = openssl_pkey_get_details($keyPair)["key"];
// 加密
$data = '敏感数据';
openssl_public_encrypt($data, $encrypted, $publicKey);
// 解密
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
Base64 编码
Base64 不是加密算法,但常用于编码二进制数据。
$data = 'some data';
$encoded = base64_encode($data);
$decoded = base64_decode($encoded);
加密扩展
PHP 的 openssl 和 mcrypt(已弃用)扩展提供了更多加密功能。建议使用 openssl,因为它更安全且维护良好。

选择加密方法时需根据具体需求决定,例如存储密码推荐使用 password_hash,传输数据推荐使用 AES 或 RSA。






