Encryption

SQLite doesn't support encrypting database files by default. Instead, you need to use a modified version of SQLite like SEE, SQLCipher, SQLiteCrypt, or wxSQLite3. This article demonstrates using an unsupported, open-source build of SQLCipher, but the information also applies to other solutions since they generally follow the same pattern.

Installation

dotnet remove package Microsoft.Data.Sqlite
dotnet add package Microsoft.Data.Sqlite.Core
dotnet add package SQLitePCLRaw.bundle_e_sqlcipher

For more information about using a different native library for encryption, see Custom SQLite versions.

Specify the key

To enable encryption on a new database, specify the key using the Password connection string keyword. Use SqliteConnectionStringBuilder to add or update the value from user input and avoid connection string injection attacks.

var connectionString = new SqliteConnectionStringBuilder(baseConnectionString)
{
    Mode = SqliteOpenMode.ReadWriteCreate,
    Password = password
}.ToString();

Important

Microsoft recommends that you use the most secure authentication flow available. If you're connecting to Azure SQL, Managed Identities for Azure resources is the recommended authentication method.

Tip

The method for encrypting and decrypting existing databases varies depending on which solution you're using. For example, you need to use the sqlcipher_export() function on SQLCipher. Check your solution's documentation for details.

Rekeying the database

If you want to change the key of an encrypted database, issue a PRAGMA rekey statement.

Unfortunately, SQLite doesn't support parameters in PRAGMA statements. Instead, use the quote() function to prevent SQL injection.

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();