| 類別 | 函數/方法 | 可逆性 | 用途 |
| 雜湊 (單向) | md5(), sha1(), hash() | 不可逆 | 完整性驗證、索引、非敏感指紋 |
| 密碼雜湊 (單向+鹽值+慢速) | password_hash(), crypt() | 不可逆 | 儲存使用者密碼 (唯一正確選擇) |
| 編碼 (可逆) | base64_encode/decode | 可逆 | 二進位資料文字化傳輸 (Email、JSON、Data URI) |
| URL 編碼 (可逆) | urlencode/urldecode, rawurlencode | 可逆 | 查詢字串參數編碼 |
各方法詳解與程式碼
1. MD5 (不建議用於密碼)
<?php
$pwd = '123456';
echo md5($pwd); // e10adc3949ba59abbe56e057f20f883e
// 固定長度 32 字元十六進位,極快,易遭彩虹表破解
2. crypt() 多演算法支援
<?php
$pwd = '123456';
// 自動產生鹽值 (建議)
$hash = crypt($pwd); // 如 $2y$10$...
// 驗證
if (crypt($pwd, $hash) === $hash) echo 'Valid';
// 指定演算法鹽值格式
// CRYPT_BLOWFISH: $2y$cost$salt$ (cost 04-31)
// CRYPT_SHA256: $5$rounds=N$salt$
// CRYPT_SHA512: $6$rounds=N$salt$
3. SHA1 (同 MD5,不建議密碼)
<?php
echo sha1('123456'); // 7c4a8d09ca3762af61e59520943dc26494f8941b
4. URL 編碼
<?php
$url = 'https://example.com/?q=中文&t=1';
$enc = urlencode($url); // 空格變 +,符合 application/x-www-form-urlencoded
$enc = rawurlencode($url); // 空格變 %20,符合 RFC 3986
echo urldecode($enc);
5. Base64 編碼
<?php
$data = '二進位資料或字串';
$enc = base64_encode($data); // 體積增大 ~33%
$dec = base64_decode($enc); // 嚴格模式 base64_decode($enc, true)
密碼儲存黃金法則:password_hash() / password_verify()
<?php
// PHP 5.5+
$hash = password_hash($password, PASSWORD_DEFAULT); // 目前 BCrypt, 未來自動升級
// 儲存 $hash 到資料庫 (長度 60+ 字元,預留 255)
if (password_verify($inputPassword, $hash)) {
// 登入成功
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
// 演算法升級,重新雜湊並更新資料庫
$newHash = password_hash($inputPassword, PASSWORD_DEFAULT);
}
}
推薦庫:phpass (舊版 PHP 相容)
若仍在 PHP 5.3/5.4,使用 phpass (Portable PHP password hashing framework),提供相容的 bcrypt 雜湊。
總結建議
- 用戶密碼:只用
password_hash() / password_verify()。
- API 簽名、資料完整性:
hash_hmac('sha256', $data, $secret)。
- 傳輸二進位:
base64_encode。
- URL 參數:
rawurlencode (RFC 3986) 或 http_build_query。
- 棄用:md5、sha1、crypt (手動)、自行設計加密演算法。
copyright ©
萬盛學電腦網 all rights reserved