傳統固定金鑰或隨資料傳送金鑰均易遭竊聽破解。採用「伺服器產生隨機金鑰 → 客戶端取得 → 雙向加密通訊」模式,每次登入金鑰不同,大幅降低重放攻擊風險。
GetKey() 取得隨機字串(如 Format('%d', [Random(MaxInt)]))。strKey 供後續解密使用。LogIn(EncUser, EncPass)。strKey := myRemoteServer.GetKey(); // 取得隨機金鑰
UserName := Ency(strUserName, strKey); // 加密使用者名稱
Password := Ency(strPassword, strKey); // 加密密碼
if myRemoteServer.LogIn(UserName, Password) then
begin
// 登入成功,後續資料傳輸同樣使用 strKey 加解密
end;
function TRemoteServer.LogIn(const UserName, Password: string): Boolean;
var
DecUser, DecPass: string;
begin
DecUser := DeEncy(UserName, strKey); // 解密
DecPass := DeEncy(Password, strKey);
// 查詢資料庫比對
Result := (DecUser = DBUser) and (DecPass = DBPass);
if Result then strKey := ''; // 單次金鑰用畢即廢棄
end;
在 TDataSetProvider.OnGetData 事件中遍歷資料集,對敏感欄位(如薪資、身分證號)呼叫 Ency(Field.AsString, strKey) 加密後再送往客戶端;OnUpdateData 中對應解密再寫入資料庫。
Password,伺服器開啟時提供。隨機金鑰交換結合對稱加密,兼顧效能與安全性,適合中小型 C/S 架構管理系統。大型系統建議引入非對稱加密(RSA/ECC)進行金鑰協商,並部署 WAF、零信任網關等纵深防禦體系。