php怎么实现加密
PHP 加密方法
PHP 提供了多种加密方式,包括哈希加密、对称加密和非对称加密。以下是常见的实现方法:
哈希加密(单向加密)
哈希加密通常用于密码存储,常用的算法有 md5、sha1 和更安全的 password_hash。

// md5 加密
$md5Hash = md5('plaintext');
// sha1 加密
$sha1Hash = sha1('plaintext');
// password_hash (推荐用于密码存储)
$passwordHash = password_hash('plaintext', PASSWORD_DEFAULT);
// 验证密码
$isValid = password_verify('plaintext', $passwordHash);
对称加密(AES)
对称加密使用相同的密钥进行加密和解密,常见算法如 AES。

// 加密
$method = 'AES-256-CBC';
$key = openssl_random_pseudo_bytes(32);
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($method));
$encrypted = openssl_encrypt('plaintext', $method, $key, 0, $iv);
// 解密
$decrypted = openssl_decrypt($encrypted, $method, $key, 0, $iv);
非对称加密(RSA)
非对称加密使用公钥和私钥,适合安全传输数据。
// 生成密钥对
$config = array(
"private_key_bits" => 2048,
"private_key_type" => OPENSSL_KEYTYPE_RSA,
);
$keyPair = openssl_pkey_new($config);
openssl_pkey_export($keyPair, $privateKey);
$publicKey = openssl_pkey_get_details($keyPair)["key"];
// 加密
openssl_public_encrypt('plaintext', $encrypted, $publicKey);
// 解密
openssl_private_decrypt($encrypted, $decrypted, $privateKey);
Base64 编码(非加密)
Base64 不是加密算法,但常用于编码二进制数据。
$encoded = base64_encode('plaintext');
$decoded = base64_decode($encoded);
注意事项
- 哈希加密是单向的,无法解密,适合存储密码。
- 对称加密需要安全地存储密钥。
- 非对称加密适合密钥交换或数字签名。
- 始终使用安全的算法(如
AES-256、RSA-2048)和随机 IV(初始化向量)。






