隨著網路交易與資料傳輸量暴增,資料加密已成為現代應用程式的基礎防線。PHP 內建多種加密函數,並支援強大的擴展庫(Mcrypt、Mhash),為開發者提供完整的密碼學工具箱。
string crypt(string $input_string [, string $salt])
支援四種演算法(由 CRYPT_SALT_LENGTH 決定):
| 演算法 | Salt 長度 |
|---|---|
| CRYPT_STD_DES | 2 字元(預設) |
| CRYPT_EXT_DES | 9 字元 |
| CRYPT_MD5 | 12 字元,以 $1$ 開頭 |
| CRYPT_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 進行 crypt 加密
$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');
print "您無權進入此區域。";
exit;
} else {
print "這是機密資料!";
}
?>
注意:預設 DES 強度較低,高安全性需求請改用 MD5 或 Blowfish,或改用下述擴展庫。
<?php
$msg = "This is some message that I just wrote";
$enc_msg = md5($msg);
print "hash: $enc_msg";
// 輸出:81ea092649ca32b5ba375e81d8f4972c (32 字元十六進位)
?>
特性:
Mcrypt 提供 22 種演算法(Blowfish、RC2、Rijndael/AES、Twofish 等)與 35 個函數,支援加密與解密。
# 下載編譯
wget ftp://argeas.cs-net.gr/pub/unix/mcrypt/mcrypt-2.5.7.tar.gz
tar -xzf mcrypt-2.5.7.tar.gz
cd mcrypt-2.5.7
./configure --disable-posix-threads
make && make install
# PHP 重新編譯
cd /path/to/php
./configure --with-mcrypt=[mcrypt安裝目錄] [其他選項]
make && make install
<?php
$string = "Applied Cryptography, by Bruce Schneier...";
$key = "Four score and twenty years ago";
$cipher_alg = MCRYPT_RIJNDAEL_128; // AES-128
// 建立初始化向量 (IV)
$iv = mcrypt_create_iv(mcrypt_get_iv_size($cipher_alg, MCRYPT_MODE_ECB), MCRYPT_RAND);
// 加密 (CBC 模式)
$encrypted_string = mcrypt_encrypt($cipher_alg, $key, $string, MCRYPT_MODE_CBC, $iv);
print "Encrypted: " . bin2hex($encrypted_string) . "<p>";
// 解密
$decrypted_string = mcrypt_decrypt($cipher_alg, $key, $encrypted_string, MCRYPT_MODE_CBC, $iv);
print "Decrypted: $decrypted_string";
?>
關鍵函數:mcrypt_encrypt()、mcrypt_decrypt()、mcrypt_create_iv()(建立 IV 確保同樣明文加密結果不同)。
支援 12 種演算法:MD5、SHA1、HAVAL、RIPEMD160、TIGER、GOST、CRC32 等。
wget https://sourceforge.net/projects/mhash/mhash-0.8.3.tar.gz
tar -xzf mhash-0.8.3.tar.gz
cd mhash-0.8.3
./configure && make && make install
cd /path/to/php
./configure --with-mhash=[mhash安裝目錄] [其他選項]
make && make install
Windows 可至 php4win.de 下載含 Mhash 的套件。
<?php
$hash_alg = MHASH_TIGER;
$message = "These are the directions to the secret fort...";
$hashed_message = mhash($hash_alg, $message);
print "The hashed message is " . bin2hex($hashed_message);
// 輸出:07a92a4db3a4177f19ec9034ae5400eb60d1a9fbb4ade461
?>
取得演算法名稱:mhash_get_hash_name($hash_alg)。
PHP 是伺服器端技術,**無法保護客戶端與伺服器間的傳輸安全**。完整安全架構必須搭配 Apache-SSL (mod_ssl) 或其他 TLS/SSL 方案,確保傳輸通道加密。
PHP 提供完整加密生態系:
crypt()(單向)、md5()(雜湊)記住:應用層加密需搭配傳輸層加密(HTTPS),才能構建真正安全的系統。