PHP 提供多種加密/編碼函數,適用場景各異。本文系統梳理單向哈希(MD5、SHA1、Crypt)、可逆編碼(Base64、URL 編碼)、以及密碼存儲的行業標準 bcrypt(推薦 phpass 库)。
string md5 ( string $str [, bool $raw_output = false ] )
raw_output=true 時為 16 字節二進制)。md5('123456') → e10adc3949ba59abbe56e057f20f883estring crypt ( string $str [, string $salt ] )
$1$ → MD5 (12 字符鹽)$2a$ → Blowfish (cost 參數 + 64 位鹽)$5$ → SHA-256 (16 字符鹽,可指定 rounds)$6$ → SHA-512 (16 字符鹽,可指定 rounds)$hash = crypt('mypassword'); // 自動生成鹽
if (crypt('mypassword', $hash) === $hash) { echo '驗證通過'; }
string sha1 ( string $str [, bool $raw_output = false ] )
raw_output=true 為 20 字節二進制)。sha1('123456') → 7c4a8d09ca3762af61e59520943dc26494f8941bstring urlencode ( string $str )
string urldecode ( string $str )
-_.)轉為 %XX,空格變 +。application/x-www-form-urlencoded 標準。!、*、' 等)。string base64_encode ( string $data )
string base64_decode ( string $data [, bool $strict = false ] )
strict=true 時遇非法字符返回 FALSE。MD5/SHA1/Crypt(無 cost) 均過快,易遭暴力破解。bcrypt 內建 cost 因子(可調整計算耗時),專為密碼設計。
<?php
require_once('phpass-03/PasswordHash.php');
$hasher = new PasswordHash(8, false); // cost=8, 不可移植(更安全)
$hash = $hasher->HashPassword('my super cool password'); // 60 字符串
// 存入數據庫...
// 驗證
$hasher->CheckPassword('wrong', $hash); // false
$hasher->CheckPassword('my super cool password', $hash); // true
?>
PasswordHash(cost, portable):cost 為 2 的指數迭代次數(4-31),portable=false 強制使用 bcrypt。| 場景 | 推薦方案 |
|---|---|
| 用戶密碼存儲 | phpass (bcrypt) |
| 數據完整性校驗(非安全) | MD5 / SHA1 |
| URL 參數傳遞 | urlencode / urldecode |
| 二進制數據文本化傳輸 | base64_encode / decode |
| 需自定義算法/鹽的舊系統兼容 | crypt() 指定鹽值格式 |
切記:不要嘗試「加密」密碼,要「哈希」密碼,並使用專門為密碼設計的慢速哈希算法(bcrypt/Argon2)。