
// 创建密码哈希
$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'; // 32字节长度
$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);
// HMAC(带密钥的哈希)
$key = 'secret_key';
$hmac = hash_hmac('sha256', $string, $key);
// 注意:Mcrypt扩展在PHP 7.1中已废弃,PHP 7.2中移除
// 建议使用OpenSSL替代