PHP 內建 crypt() 與 md5(),並可透過擴展庫 Mcrypt、Mhash 獲得工業級加密能力。本文系統整理安裝步驟、參數細節與實戰程式碼。
string crypt(string $input_string [, string $salt])
$input_string:待加密明文$salt:干擾字串,影響加密結果,防禦預計算攻擊CRYPT_SALT_LENGTH(DES 為 2,MD5 為 12)| 常數 | 演算法 | Salt 格式 |
|---|---|---|
| CRYPT_STD_DES | 標準 DES | 2 字元 |
| CRYPT_EXT_DES | 擴展 DES | 9 字元 |
| CRYPT_MD5 | MD5 | 12 字元,$1$ 開頭 |
| CRYPT_BLOWFISH | Blowfish | 16 字元,$2$ 開頭 |
<?php
// 資料庫設定
$host = "localhost"; $user = "zorro"; $pswd = "hellodolly"; $db = "users";
$authorization = 0;
if (isset($PHP_AUTH_USER) && isset($PHP_AUTH_PW)) {
mysql_pconnect($host, $user, $pswd) or die("MySQL 連線失敗");
mysql_select_db($db) or die("資料庫選擇失敗");
// 以輸入密碼前兩字元為 salt
$salt = substr($PHP_AUTH_PW, 0, 2);
$encrypted_pswd = crypt($PHP_AUTH_PW, $salt);
$query = "SELECT username FROM members
WHERE username = '$PHP_AUTH_USER'
AND password = '$encrypted_pswd'";
if (mysql_numrows(mysql_query($query)) == 1) $authorization = 1;
}
if (!$authorization) {
header('WWW-Authenticate: Basic realm="Private"');
header('HTTP/1.0 401 Unauthorized');
exit("您無權進入此區域。");
}
echo "這是機密資料!";
?>
建議:生產環境請改用 password_hash()/password_verify()(PHP 5.5+)或 Blowfish/Argon2,勿直接使用 DES。
<?php
$msg = "This is some message that I just wrote";
$hash = md5($msg); // 81ea092649ca32b5ba375e81d8f4972c
$msg2 = "This is some mesage that I just wrote"; // 少一個 's'
$hash2 = md5($msg2); // e86cf511bd5490d46d5cd61738c82c0c
?>
應用場景:檔案完整性檢查、API 簽章驗證、密碼儲存(建議加 Salt)。
Blowfish、RC2、RC4、DES、TripleDES、Rijndael-128/192/256 (AES)、Twofish、Serpent、GOST 等。
<?php
$string = "Applied Cryptography, by Bruce Schneier...";
$key = "Four score and twenty years ago";
$cipher_alg = MCRYPT_RIJNDAEL_128; // AES-128
// IV 建立:CBC 模式必須
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
$encrypted = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_CBC, $iv);
echo "Encrypted: " . bin2hex($encrypted) . "<br>";
$decrypted = mcrypt_decrypt($cipher_alg, $key, $encrypted, MCRYPT_MODE_CBC, $iv);
echo "Decrypted: $decrypted";
?>
模式說明:
MHASH_CRC32、MHASH_MD5、MHASH_SHA1、MHASH_HAVAL128/160/192/224/256、MHASH_RIPEMD160、MHASH_TIGER、MHASH_GOST
<?php
$algo = MHASH_TIGER;
$msg = "Secret directions: Two steps left, three steps right...";
$hash = mhash($algo, $msg);
echo "Hashed: " . bin2hex($hash); // 二進位轉十六進位顯示
?>
<?php
$algo = MHASH_TIGER;
echo "Hashed with " . mhash_get_hash_name($algo) . " algorithm.";
// 輸出:Hashed with TIGER algorithm.
?>
| 擴展 | 下載來源 | PHP 編譯參數 |
|---|---|---|
| Mcrypt | ftp://argeas.cs-net.gr/pub/unix/mcrypt/ | --with-mcrypt=[dir] |
| Mhash | https://sourceforge.net/projects/mhash/ | --with-mhash=[dir] |
Windows 使用者建議直接使用 php4win.de 預編譯套件。
PHP 只能處理伺服器端加密,**無法保障網路傳輸安全**。完整方案必須部署 HTTPS (TLS/SSL),否則明文傳輸過程中密鑰與資料仍可被竊聽。