加密存儲(chǔ)模型

SSL/SSH 能保護(hù)客戶端和服務(wù)器端交換的數(shù)據(jù),但 SSL/SSH 并不能保護(hù)數(shù)據(jù)庫中已有的數(shù)據(jù)。SSL 只是一個(gè)加密網(wǎng)絡(luò)數(shù)據(jù)流的協(xié)議。

如果攻擊者取得了直接訪問數(shù)據(jù)庫的許可(繞過 web 服務(wù)器),敏感數(shù)據(jù)就可能暴露或者被濫用,除非數(shù)據(jù)庫自己保護(hù)了這些信息。對(duì)數(shù)據(jù)庫內(nèi)的數(shù)據(jù)加密是減少這類風(fēng)險(xiǎn)的有效途徑,但是只有很少的數(shù)據(jù)庫提供這些加密功能。

解決這個(gè)問題最簡單的方法是創(chuàng)建自己的加密包,然后在 PHP 腳本中使用它。PHP 可以通過一些擴(kuò)展來幫助你解決這個(gè)問題,比如 OpenSSLSodium,涵蓋了多種加密算法。腳本在將數(shù)據(jù)插入數(shù)據(jù)庫之前對(duì)其進(jìn)行加密,并在檢索時(shí)對(duì)其進(jìn)行解密。更多關(guān)于加密工作的例子請(qǐng)參見參考文獻(xiàn)。

Hashing

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

// 存儲(chǔ)密碼散列
$query  sprintf("INSERT INTO users(name,pwd) VALUES('%s','%s');",
            
pg_escape_string($username),
            
password_hash($passwordPASSWORD_DEFAULT));
$result pg_query($connection$query);

// 發(fā)送請(qǐng)求來驗(yàn)證用戶密碼
$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) . '.';
}

?>