加密
SQLite 預設不支援加密資料庫檔案。 相反地,您必須使用修改過的 SQLite 版本,例如 SEE、SQLCipher、SQLiteCrypt 或 wxSQLite3。 本文示範如何使用 SQLCipher 不支援的開放原始碼組建,但資訊也適用於其他解決方案,因為它們通常會遵循相同的模式。
安裝
dotnet remove package Microsoft.Data.Sqlite
dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_e_sqlcipher
如需使用不同的原生程式庫進行加密的詳細資訊,請參閱自訂 SQLite 版本。
指定金鑰
若要在新資料庫上啟用加密,請使用 Password
連接字串關鍵字來指定金鑰。 使用 SqliteConnectionStringBuilder 從使用者輸入新增或更新值,並避免連接字串插入式攻擊。
var connectionString = new SqliteConnectionStringBuilder(baseConnectionString)
{
Mode = SqliteOpenMode.ReadWriteCreate,
Password = password
}.ToString();
重要
Microsoft建議您使用可用的最安全驗證流程。 如果您正在連接 Azure SQL,建議使用的驗證方法為 Azure 資源受控識別。
提示
加密和解密現有資料庫的方法會因您使用的解決方案而有所不同。 例如,您必須在 SQLCipher 上使用 sqlcipher_export()
函式。 請查看解決方案的文件以取得詳細資料。
重設資料庫金鑰
如果您想要變更加密資料庫的金鑰,請發出 PRAGMA rekey
陳述式。
可惜的是,SQLite 不支援 PRAGMA
陳述式中的參數。 請改用 quote()
函式來防止 SQL 插入。
var command = connection.CreateCommand();
command.CommandText = "SELECT quote($newPassword);";
command.Parameters.AddWithValue("$newPassword", newPassword);
var quotedNewPassword = (string)command.ExecuteScalar();
command.CommandText = "PRAGMA rekey = " + quotedNewPassword;
command.Parameters.Clear();
command.ExecuteNonQuery();