SSL/SSH 能保護客戶(hù)端和服務(wù)器端交換的數據,但 SSL/SSH 并不能保護數據庫中已有的數據。SSL 只是一個(gè)加密網(wǎng)絡(luò )數據流的協(xié)議。
如果攻擊者取得了直接訪(fǎng)問(wèn)數據庫的許可(繞過(guò) web 服務(wù)器),敏感數據就可能暴露或者被濫用,除非數據庫自己保護了這些信息。對數據庫內的數據加密是減少這類(lèi)風(fēng)險的有效途徑,但是只有很少的數據庫提供這些加密功能。
解決這個(gè)問(wèn)題最簡(jiǎn)單的方法是創(chuàng )建自己的加密包,然后在 PHP 腳本中使用它。PHP 可以通過(guò)一些擴展來(lái)幫助你解決這個(gè)問(wèn)題,比如 OpenSSL 和 Sodium,涵蓋了多種加密算法。腳本在將數據插入數據庫之前對其進(jìn)行加密,并在檢索時(shí)對其進(jìn)行解密。更多關(guān)于加密工作的例子請參見(jiàn)參考文獻。
In the case of truly hidden data, if its raw representation is not needed (i.e. will not be displayed), hashing should be taken into consideration. The well-known example for hashing is storing the cryptographic hash of a password in a database, instead of the password itself.
The password functions provide a convenient way to hash sensitive data and work with these hashes.
password_hash() is used to hash a given string using the strongest algorithm currently available and password_verify() checks whether the given password matches the hash stored in database.
示例 #1 Hashing password field
<?php
// 存儲密碼散列
$query = sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
pg_escape_string($username),
password_hash($password, PASSWORD_DEFAULT));
$result = pg_query($connection, $query);
// 發(fā)送請求來(lái)驗證用戶(hù)密碼
$query = sprintf("SELECT pwd FROM users WHERE name='%s';",
pg_escape_string($username));
$row = pg_fetch_assoc(pg_query($connection, $query));
if ($row && password_verify($password, $row['pwd'])) {
echo 'Welcome, ' . htmlspecialchars($username) . '!';
} else {
echo 'Authentication failed for ' . htmlspecialchars($username) . '.';
}
?>