共用方式為


加密

SQLite 預設不支援加密資料庫檔案。 相反地,您必須使用已修改的 SQLite 版本,例如 SQLCipherSQLiteCryptwxSQLite3。 本文示範了使用一個不受支持的開源版本的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();