I recently ran a series of experiments to answer one question: can a single, password-encrypted SQLite file in .NET 10 comfortably hold millions of rows, search them in several languages, and protect its contents properly? This post walks through the four tests I ran, the code for each one, the numbers I measured, and the problems I hit along the way (there were a few).
Everything below is plain C# console code, so you can copy it, run it, and compare the results on your own machine.
- Setup and packages
- Test 1: an encrypted file, created and re-opened
- Test 2: 3 million rows, full-text search and timings
- Test 3: full-text search in Arabic, Chinese, Russian, French and Spanish
- Test 4: key wrapping, a recovery key and changing the password
- Troubleshooting: everything that broke
- Summary
1. Setup and packages
I used .NET 10 on Windows 11 with a plain console project. The encryption comes from SQLite3 Multiple Ciphers, which is a drop-in build of SQLite that adds file encryption. In .NET you use it through Microsoft.Data.Sqlite.Core plus a bundle package that carries the native library.
dotnet new console -n SqliteEncryptionLab -f net10.0 cd SqliteEncryptionLab dotnet add package Microsoft.Data.Sqlite.Core dotnet add package SQLite3MC.PCLRaw.bundle dotnet list package
After dotnet list package you should see exactly these two top-level packages (the versions are the ones I had):
Top-level Package Requested Resolved > Microsoft.Data.Sqlite.Core 11.0.0 11.0.0 > SQLite3MC.PCLRaw.bundle 2.7.1 2.7.1
Test 4 also needs an Argon2id implementation, which I added only for that test:
dotnet add package Konscious.Security.Cryptography.Argon2
Use
Microsoft.Data.Sqlite.Core, not the full Microsoft.Data.Sqlite package. The full package brings its own unencrypted SQLite and conflicts with the encrypted bundle. And do not leave more than one SQLite "bundle" package in the project at the same time.
Run every test in Release mode, because debug builds distort timings:
dotnet run -c Release
2. Test 1: an encrypted file, created and re-opened
The first test is deliberately tiny. It proves four things: the file can be created with a password, it opens with the right password, it refuses the wrong one, and the text cannot be found inside the raw file.
Replace Program.cs with this:
using Microsoft.Data.Sqlite;
SQLitePCL.Batteries.Init();
const string path = "test.db";
if (File.Exists(path)) File.Delete(path);
static SqliteConnection Open(string path, string password)
{
var cs = new SqliteConnectionStringBuilder
{
DataSource = path,
Password = password
}.ToString();
var connection = new SqliteConnection(cs);
connection.Open();
return connection;
}
// 1) Create an encrypted file and insert one row
using (var c = Open(path, "correct-password"))
{
using var cmd = c.CreateCommand();
cmd.CommandText =
"CREATE TABLE T(Id INTEGER PRIMARY KEY, Txt TEXT);" +
"INSERT INTO T(Txt) VALUES ('secret text');";
cmd.ExecuteNonQuery();
}
// 2) Open with the correct password
using (var c = Open(path, "correct-password"))
{
using var cmd = c.CreateCommand();
cmd.CommandText = "SELECT Txt FROM T;";
Console.WriteLine("Correct password => " + cmd.ExecuteScalar());
}
// 3) Open with a wrong password (must fail)
try
{
using var c = Open(path, "wrong-password");
using var cmd = c.CreateCommand();
cmd.CommandText = "SELECT Txt FROM T;";
Console.WriteLine("Wrong password => " + cmd.ExecuteScalar());
}
catch (SqliteException ex)
{
Console.WriteLine("Wrong password => rejected as expected: " + ex.Message);
}
// 4) Is the plain text visible in the raw file?
SqliteConnection.ClearAllPools(); // release the file lock held by the connection pool
var raw = File.ReadAllBytes(path);
var text = System.Text.Encoding.UTF8.GetString(raw);
Console.WriteLine("Plain text visible in raw file? " + text.Contains("secret"));
Expected output:
Correct password => secret text Wrong password => rejected as expected: SQLite Error 26: 'file is not a database'. Plain text visible in raw file? False
Two details worth knowing:
- A wrong password does not fail on
Open(). The connection opens fine, and the error appears on the first real query. In real code, run a cheap check such asSELECT count(*) FROM sqlite_masterright after opening to validate the key. - Connections are pooled, so the file stays locked after
usingends. WithoutSqliteConnection.ClearAllPools()the finalFile.ReadAllBytesthrows "The process cannot access the file because it is being used by another process". SettingPooling = falsein the connection string is the alternative.
3. Test 2: 3 million rows, full-text search and timings
Next I wanted real numbers. The program below creates an encrypted database, fills it with synthetic rows spread over 40 years, builds a full-text index, and then times the queries an application would actually run.
Design decisions
| Decision | Why |
|---|---|
| Timestamps stored as integer Unix seconds (UTC) | Small, fast to sort, and not limited to dates after 1970. |
An extra CreatedDay column holding yyyymmdd | Makes "how many rows per day in this month" a simple indexed range query. |
Composite index (Priority, CreatedAt DESC, Id DESC) | Serves "newest first within a priority" without sorting. |
Keyset pagination instead of OFFSET | Page 10,000 costs the same as page 1. |
FTS5 table with external content (content='Item') | The text is not stored twice. |
| FTS triggers created after the bulk load | Much faster loading. The index is built once with 'rebuild'. |
WAL journal, synchronous=NORMAL, 64 MB cache | Good write speed with sane durability. |
Partial index on PinnedUntil | Only a tiny fraction of rows are ever pinned. |
The program
I started with TotalRows = 200_000 to check that everything worked (about a minute, 232 MB file), then changed it to 3_000_000. Make sure you have roughly 10 GB of free disk space for the full run.
Show the full benchmark program (about 330 lines)
using System.Diagnostics;
using System.Text;
using Microsoft.Data.Sqlite;
SQLitePCL.Batteries.Init();
// Start with 200_000 to check that everything works, then raise it to 3_000_000
const int TotalRows = 3_000_000;
const int BatchSize = 50_000;
const string path = "bench.db";
const string password = "test-password-123";
foreach (var f in new[] { path, path + "-wal", path + "-shm" })
if (File.Exists(f)) File.Delete(f);
// ---------- Helpers ----------
static SqliteConnection Open(string path, string password)
{
var cs = new SqliteConnectionStringBuilder
{
DataSource = path,
Password = password
}.ToString();
var connection = new SqliteConnection(cs);
connection.Open();
Exec(connection, "PRAGMA foreign_keys = ON;");
Exec(connection, "PRAGMA journal_mode = WAL;");
Exec(connection, "PRAGMA synchronous = NORMAL;");
Exec(connection, "PRAGMA temp_store = MEMORY;");
Exec(connection, "PRAGMA cache_size = -65536;");
return connection;
}
static void Exec(SqliteConnection c, string sql, SqliteTransaction? tx = null)
{
using var cmd = c.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
static long UnixNow() => DateTimeOffset.UtcNow.ToUnixTimeSeconds();
static int DayOf(long unixSeconds)
{
var d = DateTimeOffset.FromUnixTimeSeconds(unixSeconds).UtcDateTime;
return d.Year * 10000 + d.Month * 100 + d.Day;
}
// Runs a query, reads every row, returns the row count
static int Run(SqliteConnection c, string sql, params (string Name, object Value)[] ps)
{
using var cmd = c.CreateCommand();
cmd.CommandText = sql;
foreach (var (name, value) in ps) cmd.Parameters.AddWithValue(name, value);
using var r = cmd.ExecuteReader();
int rows = 0;
while (r.Read()) rows++;
return rows;
}
static void Bench(string name, int runs, Func<int> action)
{
var times = new List<double>();
int rows = 0;
for (int i = 0; i < runs; i++)
{
var sw = Stopwatch.StartNew();
rows = action();
sw.Stop();
times.Add(sw.Elapsed.TotalMilliseconds);
}
Console.WriteLine($"{name,-46} rows={rows,-7} first={times[0],9:F1} ms best={times.Min(),9:F1} ms");
}
static void PrintSizes(string path)
{
long main = File.Exists(path) ? new FileInfo(path).Length : 0;
long wal = File.Exists(path + "-wal") ? new FileInfo(path + "-wal").Length : 0;
Console.WriteLine($"File size: {main / 1024.0 / 1024.0:F1} MB (WAL: {wal / 1024.0 / 1024.0:F1} MB)");
}
// File.ReadAllBytes fails above 2 GB, so scan the file in chunks instead
static bool FileContains(string path, string needle)
{
var pattern = Encoding.UTF8.GetBytes(needle);
const int chunkSize = 16 * 1024 * 1024;
var buffer = new byte[chunkSize + pattern.Length];
int carry = 0;
using var fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
int read;
while ((read = fs.Read(buffer, carry, chunkSize)) > 0)
{
int total = carry + read;
if (buffer.AsSpan(0, total).IndexOf(pattern) >= 0) return true;
// keep the tail so a match split across two chunks is not missed
carry = Math.Min(pattern.Length - 1, total);
Array.Copy(buffer, total - carry, buffer, 0, carry);
}
return false;
}
// ---------- Schema ----------
const string schemaBase = """
CREATE TABLE Label (
Id INTEGER PRIMARY KEY CHECK (Id BETWEEN 0 AND 255),
Name TEXT NOT NULL,
ColorR INTEGER NOT NULL CHECK (ColorR BETWEEN 0 AND 255),
ColorG INTEGER NOT NULL CHECK (ColorG BETWEEN 0 AND 255),
ColorB INTEGER NOT NULL CHECK (ColorB BETWEEN 0 AND 255)
);
CREATE TABLE Item (
Id INTEGER PRIMARY KEY,
Content TEXT NOT NULL,
CreatedAt INTEGER NOT NULL, -- Unix seconds, UTC
CreatedDay INTEGER NOT NULL, -- yyyymmdd
Priority INTEGER NOT NULL DEFAULT 2 CHECK (Priority BETWEEN 0 AND 4),
PinnedUntil INTEGER NULL, -- Unix seconds, UTC
Direction INTEGER NOT NULL DEFAULT 0 CHECK (Direction BETWEEN 0 AND 2)
);
CREATE TABLE ItemLabel (
ItemId INTEGER NOT NULL REFERENCES Item(Id) ON DELETE CASCADE,
LabelId INTEGER NOT NULL REFERENCES Label(Id),
PRIMARY KEY (ItemId, LabelId)
) WITHOUT ROWID;
CREATE INDEX IX_Item_List ON Item (Priority, CreatedAt DESC, Id DESC);
CREATE INDEX IX_Item_Day ON Item (CreatedDay);
CREATE INDEX IX_Item_Pinned ON Item (PinnedUntil) WHERE PinnedUntil IS NOT NULL;
CREATE INDEX IX_ItemLabel_Label ON ItemLabel (LabelId, ItemId);
-- Full-text index with external content (the text is not stored twice)
CREATE VIRTUAL TABLE ItemFts USING fts5(
Content,
content = 'Item',
content_rowid = 'Id',
tokenize = 'unicode61 remove_diacritics 2'
);
PRAGMA user_version = 1;
""";
// Triggers are created AFTER the bulk load (much faster loading)
const string schemaTriggers = """
CREATE TRIGGER Item_ai AFTER INSERT ON Item BEGIN
INSERT INTO ItemFts(rowid, Content) VALUES (new.Id, new.Content);
END;
CREATE TRIGGER Item_ad AFTER DELETE ON Item BEGIN
INSERT INTO ItemFts(ItemFts, rowid, Content) VALUES ('delete', old.Id, old.Content);
END;
CREATE TRIGGER Item_au AFTER UPDATE OF Content ON Item BEGIN
INSERT INTO ItemFts(ItemFts, rowid, Content) VALUES ('delete', old.Id, old.Content);
INSERT INTO ItemFts(rowid, Content) VALUES (new.Id, new.Content);
END;
""";
Console.WriteLine($"Target: {TotalRows:N0} rows");
Console.WriteLine();
// ---------- Create schema + seed 256 labels ----------
using (var c = Open(path, password))
{
using var tx = c.BeginTransaction();
Exec(c, schemaBase, tx);
using var cmd = c.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText =
"INSERT INTO Label (Id, Name, ColorR, ColorG, ColorB) VALUES ($id,$name,$r,$g,$b);";
var pId = cmd.Parameters.Add("$id", SqliteType.Integer);
var pName = cmd.Parameters.Add("$name", SqliteType.Text);
var pR = cmd.Parameters.Add("$r", SqliteType.Integer);
var pG = cmd.Parameters.Add("$g", SqliteType.Integer);
var pB = cmd.Parameters.Add("$b", SqliteType.Integer);
for (int i = 0; i < 256; i++)
{
pId.Value = i;
pName.Value = i == 0 ? "General" : i == 255 ? "Other" : $"Label {i}";
pR.Value = (i * 37) % 256;
pG.Value = (i * 91) % 256;
pB.Value = (i * 53) % 256;
cmd.ExecuteNonQuery();
}
tx.Commit();
}
// ---------- Vocabulary (skewed so some words are common and some are rare) ----------
var rnd = new Random(12345);
string[] syllables = { "ka", "lo", "mi", "ra", "te", "no", "su", "vi", "ba", "de",
"fo", "gi", "hu", "ji", "ze", "qu", "pa", "wo", "xa", "yu" };
var vocab = new string[5000];
for (int i = 0; i < vocab.Length; i++)
{
int parts = rnd.Next(2, 5);
var w = new StringBuilder();
for (int p = 0; p < parts; p++) w.Append(syllables[rnd.Next(syllables.Length)]);
vocab[i] = w.ToString() + i; // the numeric suffix keeps every word unique
}
vocab[0] = "common"; // a very frequent word
vocab[3000] = "database"; // a medium-frequency word
// ---------- Bulk load ----------
Console.WriteLine("=== BULK LOAD ===");
var total = Stopwatch.StartNew();
long endTime = UnixNow();
long startTime = endTime - 40L * 365 * 86400; // 40 years of history
double step = (double)(endTime - startTime) / TotalRows;
using (var c = Open(path, password))
{
using var rowCmd = c.CreateCommand();
rowCmd.CommandText =
"INSERT INTO Item (Id, Content, CreatedAt, CreatedDay, Priority, PinnedUntil, Direction) " +
"VALUES ($id,$content,$date,$day,$pri,$pin,$dir);";
var rId = rowCmd.Parameters.Add("$id", SqliteType.Integer);
var rContent = rowCmd.Parameters.Add("$content", SqliteType.Text);
var rDate = rowCmd.Parameters.Add("$date", SqliteType.Integer);
var rDay = rowCmd.Parameters.Add("$day", SqliteType.Integer);
var rPri = rowCmd.Parameters.Add("$pri", SqliteType.Integer);
var rPin = rowCmd.Parameters.Add("$pin", SqliteType.Integer);
var rDir = rowCmd.Parameters.Add("$dir", SqliteType.Integer);
using var labelCmd = c.CreateCommand();
labelCmd.CommandText = "INSERT INTO ItemLabel (ItemId, LabelId) VALUES ($n,$t);";
var lItem = labelCmd.Parameters.Add("$n", SqliteType.Integer);
var lLabel = labelCmd.Parameters.Add("$t", SqliteType.Integer);
var sb = new StringBuilder(2048);
var batchTimer = Stopwatch.StartNew();
for (int batchStart = 0; batchStart < TotalRows; batchStart += BatchSize)
{
using var tx = c.BeginTransaction();
rowCmd.Transaction = tx;
labelCmd.Transaction = tx;
int batchEnd = Math.Min(batchStart + BatchSize, TotalRows);
for (int i = batchStart; i < batchEnd; i++)
{
// Content: 2..200 words, skewed toward the low-index words
int words = 2 + (int)(Math.Pow(rnd.NextDouble(), 2) * 199);
sb.Clear();
for (int w = 0; w < words; w++)
{
if (w > 0) sb.Append(' ');
sb.Append(vocab[(int)(Math.Pow(rnd.NextDouble(), 2) * vocab.Length)]);
}
// A unique word planted in exactly 3 rows (rare-word search test)
if (i == TotalRows / 2 || i == TotalRows / 3 || i == TotalRows / 5)
sb.Append(" zebraquartz");
// Chronological order, like real usage
long when = startTime + (long)(i * step) + rnd.Next(0, (int)Math.Max(1, step));
double r = rnd.NextDouble();
int priority = r < 0.02 ? 0 : r < 0.10 ? 1 : r < 0.80 ? 2 : r < 0.95 ? 3 : 4;
long? pinned = rnd.NextDouble() < 0.0001 ? endTime + 30L * 86400 : null;
rId.Value = i + 1;
rContent.Value = sb.ToString();
rDate.Value = when;
rDay.Value = DayOf(when);
rPri.Value = priority;
rPin.Value = (object?)pinned ?? DBNull.Value;
rDir.Value = 0;
rowCmd.ExecuteNonQuery();
lItem.Value = i + 1;
lLabel.Value = rnd.NextDouble() < 0.6 ? 0 : rnd.Next(1, 256);
labelCmd.ExecuteNonQuery();
}
tx.Commit();
Console.WriteLine($" {batchEnd,12:N0} rows ({batchTimer.Elapsed.TotalSeconds:F0} s elapsed)");
}
}
Console.WriteLine($"Insert time: {total.Elapsed.TotalSeconds:F1} s");
// ---------- Build the full-text index, create triggers, gather statistics ----------
using (var c = Open(path, password))
{
var sw = Stopwatch.StartNew();
Exec(c, "INSERT INTO ItemFts(ItemFts) VALUES ('rebuild');");
Console.WriteLine($"FTS5 rebuild: {sw.Elapsed.TotalSeconds:F1} s");
Exec(c, schemaTriggers);
sw.Restart();
Exec(c, "ANALYZE;");
Console.WriteLine($"ANALYZE: {sw.Elapsed.TotalSeconds:F1} s");
Exec(c, "PRAGMA wal_checkpoint(TRUNCATE);");
}
SqliteConnection.ClearAllPools();
PrintSizes(path);
Console.WriteLine();
// ---------- Benchmarks ----------
Console.WriteLine("=== OPEN TIME (includes key derivation) ===");
{
var sw = Stopwatch.StartNew();
using var tmp = Open(path, password);
Run(tmp, "SELECT count(*) FROM sqlite_master;");
Console.WriteLine($"Open + first query: {sw.Elapsed.TotalMilliseconds:F1} ms");
}
Console.WriteLine();
using (var c = Open(path, password))
{
long now = UnixNow();
// Cursor for a deep page (found once with OFFSET; the benchmark itself uses keyset paging)
long deepDate, deepId;
using (var cmd = c.CreateCommand())
{
cmd.CommandText = "SELECT CreatedAt, Id FROM Item WHERE Priority = 2 " +
"ORDER BY CreatedAt DESC, Id DESC LIMIT 1 OFFSET $off;";
cmd.Parameters.AddWithValue("$off", TotalRows / 4);
using var r = cmd.ExecuteReader();
r.Read();
deepDate = r.GetInt64(0);
deepId = r.GetInt64(1);
}
Console.WriteLine("=== LISTS ===");
Bench("Pinned items", 3, () => Run(c,
"SELECT Id, substr(Content, 1, 60) FROM Item WHERE PinnedUntil > $now ORDER BY PinnedUntil;",
("$now", now)));
Bench("List page 1 (Priority 2, 50 rows)", 3, () => Run(c,
"SELECT Id, substr(Content, 1, 60) FROM Item WHERE Priority = 2 " +
"ORDER BY CreatedAt DESC, Id DESC LIMIT 50;"));
Bench("List deep page (keyset, 50 rows)", 3, () => Run(c,
"SELECT Id, substr(Content, 1, 60) FROM Item WHERE Priority = 2 " +
"AND (CreatedAt, Id) < ($d, $i) ORDER BY CreatedAt DESC, Id DESC LIMIT 50;",
("$d", deepDate), ("$i", deepId)));
Bench("List page 1 (Priority 0)", 3, () => Run(c,
"SELECT Id, substr(Content, 1, 60) FROM Item WHERE Priority = 0 " +
"ORDER BY CreatedAt DESC, Id DESC LIMIT 50;"));
Console.WriteLine();
Console.WriteLine("=== DAILY COUNTS ===");
Bench("Month counts (current month)", 3, () => Run(c,
"SELECT CreatedDay, COUNT(*) FROM Item WHERE CreatedDay BETWEEN $a AND $b GROUP BY CreatedDay;",
("$a", DayOf(now) / 100 * 100 + 1), ("$b", DayOf(now) / 100 * 100 + 31)));
Bench("Month counts (20 years ago)", 3, () => Run(c,
"SELECT CreatedDay, COUNT(*) FROM Item WHERE CreatedDay BETWEEN $a AND $b GROUP BY CreatedDay;",
("$a", (DateTime.UtcNow.Year - 20) * 10000 + 301), ("$b", (DateTime.UtcNow.Year - 20) * 10000 + 331)));
Bench("Items of one day (50 rows)", 3, () => Run(c,
"SELECT Id, substr(Content, 1, 60) FROM Item WHERE CreatedDay = $d ORDER BY CreatedAt DESC LIMIT 50;",
("$d", (DateTime.UtcNow.Year - 10) * 10000 + 615)));
Console.WriteLine();
Console.WriteLine("=== FULL-TEXT SEARCH ===");
Bench("Rare word 'zebraquartz'", 3, () => Run(c,
"SELECT n.Id, substr(n.Content, 1, 60) FROM ItemFts f JOIN Item n ON n.Id = f.rowid " +
"WHERE ItemFts MATCH $q ORDER BY rank LIMIT 20;", ("$q", "zebraquartz")));
Bench("Medium word 'database' (rank, top 20)", 3, () => Run(c,
"SELECT n.Id, substr(n.Content, 1, 60) FROM ItemFts f JOIN Item n ON n.Id = f.rowid " +
"WHERE ItemFts MATCH $q ORDER BY rank LIMIT 20;", ("$q", "database")));
Bench("Common word 'common' (rank, top 20)", 3, () => Run(c,
"SELECT n.Id, substr(n.Content, 1, 60) FROM ItemFts f JOIN Item n ON n.Id = f.rowid " +
"WHERE ItemFts MATCH $q ORDER BY rank LIMIT 20;", ("$q", "common")));
Bench("Common word 'common' (newest first)", 3, () => Run(c,
"SELECT n.Id, substr(n.Content, 1, 60) FROM ItemFts f JOIN Item n ON n.Id = f.rowid " +
"WHERE ItemFts MATCH $q ORDER BY f.rowid DESC LIMIT 20;", ("$q", "common")));
Console.WriteLine();
Console.WriteLine("=== WRITES ===");
Bench("Insert one row (with FTS trigger)", 20, () =>
{
long when = UnixNow();
using var cmd = c.CreateCommand();
cmd.CommandText =
"INSERT INTO Item (Content, CreatedAt, CreatedDay, Priority, Direction) " +
"VALUES ('benchmark row about common words', $d, $day, 2, 0); " +
"INSERT INTO ItemLabel (ItemId, LabelId) VALUES (last_insert_rowid(), 0);";
cmd.Parameters.AddWithValue("$d", when);
cmd.Parameters.AddWithValue("$day", DayOf(when));
cmd.ExecuteNonQuery();
return 1;
});
Bench("Bulk update: Priority 2 -> 3 (5000 rows)", 1, () =>
{
long cutoff = UnixNow() - 183L * 86400; // about 6 months
using var cmd = c.CreateCommand();
cmd.CommandText =
"UPDATE Item SET Priority = 3 WHERE Id IN " +
"(SELECT Id FROM Item WHERE Priority = 2 AND CreatedAt < $cutoff LIMIT 5000);";
cmd.Parameters.AddWithValue("$cutoff", cutoff);
return cmd.ExecuteNonQuery();
});
Console.WriteLine();
Console.WriteLine("=== FOR COMPARISON (what NOT to do) ===");
Bench("COUNT(*) over all rows", 2, () => Run(c, "SELECT COUNT(*) FROM Item;"));
}
// ---------- Confirm the file is still encrypted ----------
SqliteConnection.ClearAllPools();
Console.WriteLine();
Console.WriteLine("Plain text visible in raw file? " + FileContains(path, "common"));
Results with 3,000,000 rows
"First" is the first execution (cold cache), which is closest to what a user sees right after launching the program. "Best" is the fastest of the repeated runs.
| Operation | First | Best |
|---|---|---|
| Insert 3,000,000 rows | 186.6 s | |
Build FTS5 index (rebuild) | 162.8 s | |
ANALYZE | 3.8 s | |
| Final file size | 3,469 MB | |
| Open file + first query (includes key derivation) | 312 ms | |
| Pinned items (294 rows) | 31.0 ms | 0.7 ms |
| List page 1 (Priority 2, 50 rows) | 1.7 ms | 0.2 ms |
| List deep page (keyset, 50 rows) | 1.5 ms | 0.3 ms |
| List page 1 (Priority 0) | 2.7 ms | 0.1 ms |
| Month counts (current month) | 3.5 ms | 0.6 ms |
| Month counts (20 years ago) | 2.1 ms | 0.8 ms |
| Rows of one day (50 rows) | 2.5 ms | 0.2 ms |
| Search: rare word | 187.2 ms | 0.5 ms |
| Search: medium-frequency word, ranked | 323.8 ms | 55.7 ms |
| Search: very common word, ranked | 4,318.5 ms | 4,066.3 ms |
| Search: very common word, newest first | 1.5 ms | 0.7 ms |
| Insert one row (with FTS trigger) | 17.9 ms | 0.5 ms |
| Bulk update of 5,000 rows | 438.8 ms | - |
COUNT(*) over all rows (what not to do) | 255.9 ms | 2.0 ms |
What I took from the numbers
- SQLite handles 3 million rows without effort. Everything that is index-backed (lists, deep pages, daily counts, inserts) finishes in a few milliseconds, even on the first run. A file of about 3.5 GB is perfectly manageable.
- Encryption is cheap. Opening the encrypted file and running the first query took 312 ms, and that includes the key derivation.
- The one real problem is ranked search for a very common word. Ordering by relevance (
ORDER BY rank) has to score every matching row, so it took over 4 seconds. Ordering the same search byrowid DESC(newest first) stops after the first 20 matches and took 1.5 ms. If your users mostly want recent results, make that the default and treat relevance ranking as an option. One caveat:rowid DESCequals "newest first" only while rows are inserted in chronological order. - Avoid
COUNT(*)on the whole table on a hot path. Keep a counter in a small table if you need one. - Building the full-text index is a one-off cost (163 s here), not something that happens during normal use.
The numbers come from my own machine and from synthetic random data, so treat them as an indication of what SQLite can do, not as a promise for your data.
4. Test 3: full-text search in Arabic, Chinese, Russian, French and Spanish
The default FTS5 tokenizer (unicode61) works well for English, but I wanted to know how it behaves for other writing systems. I compared three approaches on the same sentences:
| Method | Description |
|---|---|
| A | unicode61 on the text as it is. |
| B | The trigram tokenizer, which matches parts of words. |
| C | unicode61 on text normalized in the application before indexing, with the same normalization applied to every search query. |
The normalization in method C does four things:
- Arabic: removes diacritics and tatweel, and unifies the alef forms, alef maqsura and ta marbuta.
- Latin scripts: strips accents (so reunion finds Réunion) and lowercases.
- Chinese, Japanese, Korean: puts every character in its own token, so two- and three-character queries work without a word segmenter.
- Arabic: removes the definite article (al-) from long words with a simple rule, so kitab and al-kitab match each other.
The original text stays untouched in your main table. Only the copy inside the search index is normalized.
Show the full test program (about 300 lines)
Save the file as UTF-8, otherwise the Arabic, Chinese and Russian test strings will be corrupted.
using System.Diagnostics;
using System.Globalization;
using System.Text;
using Microsoft.Data.Sqlite;
SQLitePCL.Batteries.Init();
const string password = "test-password-123";
const int SizeTestRows = 100_000;
// ---------- Test data (save this file as UTF-8) ----------
var samples = new (int Id, string Lang, string Text)[]
{
(1, "en", "Weather report for the weekend"),
(2, "ar", "الكتاب هو أفضل صديق"),
(3, "ar", "كِتَابٌ جَدِيدٌ عن قواعد البيانات"),
(4, "ar", "اجتمع أحمد مع الفريق"),
(5, "zh", "今天天气很好"),
(6, "zh", "数据库设计会议记录"),
(7, "zh", "我们需要备份数据库"),
(8, "ru", "Погода сегодня хорошая"),
(9, "ru", "Встреча о базе данных"),
(10, "fr", "Les enfants jouent dans le jardin"),
(11, "fr", "Réunion sur la base de données"),
(12, "es", "El gato duerme en el sofá"),
(13, "es", "Reunión sobre la base de datos"),
};
// (label, query, expected row ids)
var tests = new (string Label, string Query, int[] Expected)[]
{
("en word", "weather", new[] { 1 }),
("ar word, no prefix", "كتاب", new[] { 2, 3 }),
("ar word, with al-", "الكتاب", new[] { 2, 3 }),
("ar alef variants", "احمد", new[] { 4 }),
("zh 3 chars", "数据库", new[] { 6, 7 }),
("zh 2 chars", "数据", new[] { 6, 7 }),
("zh 2 chars (backup)", "备份", new[] { 7 }),
("ru lowercase query", "погода", new[] { 8 }),
("ru inflected form", "базе", new[] { 9 }),
("fr accents", "reunion", new[] { 11, 13 }),
("fr word", "enfants", new[] { 10 }),
("es word", "gato", new[] { 12 }),
};
// ---------- Helpers ----------
static SqliteConnection Open(string path, string password, bool fast = false)
{
var cs = new SqliteConnectionStringBuilder { DataSource = path, Password = password }.ToString();
var c = new SqliteConnection(cs);
c.Open();
Exec(c, "PRAGMA journal_mode = WAL;");
Exec(c, fast ? "PRAGMA synchronous = OFF;" : "PRAGMA synchronous = NORMAL;");
return c;
}
static void Exec(SqliteConnection c, string sql, SqliteTransaction? tx = null)
{
using var cmd = c.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
static void DeleteDb(string path)
{
SqliteConnection.ClearAllPools();
foreach (var f in new[] { path, path + "-wal", path + "-shm" })
if (File.Exists(f)) File.Delete(f);
}
static bool IsCjk(char ch) =>
(ch >= '\u4E00' && ch <= '\u9FFF') || (ch >= '\u3400' && ch <= '\u4DBF') ||
(ch >= '\u3040' && ch <= '\u30FF') || (ch >= '\uAC00' && ch <= '\uD7AF');
// Method C: normalize text in the application before indexing (and before searching)
static string PrepareForIndex(string text)
{
// 1) Arabic: drop diacritics and tatweel, unify alef / ya / ta marbuta
var sb = new StringBuilder(text.Length);
foreach (var ch in text)
{
if ((ch >= '\u064B' && ch <= '\u065F') || ch == '\u0670' || ch == '\u0640') continue;
sb.Append(ch switch
{
'\u0623' or '\u0625' or '\u0622' or '\u0671' => '\u0627',
'\u0649' => '\u064A',
'\u0629' => '\u0647',
_ => ch
});
}
// 2) Strip combining marks (Latin accents) and lowercase
var decomposed = sb.ToString().Normalize(NormalizationForm.FormD);
var clean = new StringBuilder(decomposed.Length);
foreach (var ch in decomposed)
if (CharUnicodeInfo.GetUnicodeCategory(ch) != UnicodeCategory.NonSpacingMark)
clean.Append(ch);
var lower = clean.ToString().Normalize(NormalizationForm.FormC).ToLowerInvariant();
// 3) Tokenize: every CJK character becomes its own token
var tokens = new List<string>();
var cur = new StringBuilder();
void Flush()
{
if (cur.Length > 0) { tokens.Add(cur.ToString()); cur.Clear(); }
}
foreach (var ch in lower)
{
if (IsCjk(ch)) { Flush(); tokens.Add(ch.ToString()); }
else if (char.IsLetterOrDigit(ch)) cur.Append(ch);
else Flush();
}
Flush();
// 4) Arabic: strip the definite article "al-" from long words (a crude heuristic)
for (int i = 0; i < tokens.Count; i++)
{
var t = tokens[i];
if (t.Length >= 5 && t[0] == '\u0627' && t[1] == '\u0644')
tokens[i] = t.Substring(2);
}
return string.Join(' ', tokens);
}
static string Quote(string s) => "\"" + s.Replace("\"", "\"\"") + "\"";
static List<long> SearchIds(SqliteConnection c, string table, string expr)
{
var ids = new List<long>();
if (string.IsNullOrWhiteSpace(expr)) return ids;
try
{
using var cmd = c.CreateCommand();
cmd.CommandText = $"SELECT rowid FROM {table} WHERE {table} MATCH $q ORDER BY rowid;";
cmd.Parameters.AddWithValue("$q", expr);
using var r = cmd.ExecuteReader();
while (r.Read()) ids.Add(r.GetInt64(0));
}
catch (SqliteException) { /* e.g. query too short for trigram */ }
return ids;
}
static string Describe(List<long> found, int[] expected)
{
var f = found.ToHashSet();
var e = expected.Select(x => (long)x).ToHashSet();
string status = f.SetEquals(e) ? "OK"
: f.Count == 0 ? "none"
: e.IsSubsetOf(f) ? "EXTRA"
: "MISS";
return $"{status} [{string.Join(",", found)}]";
}
static string MethodQuery(char method, string raw) =>
method == 'C' ? Quote(PrepareForIndex(raw)) : Quote(raw);
// =====================================================================
// PART 1: correctness on a small multilingual set
// =====================================================================
const string correctnessFile = "fts_lang_test.db";
DeleteDb(correctnessFile);
using (var c = Open(correctnessFile, password))
{
Exec(c, "CREATE VIRTUAL TABLE FtsA USING fts5(Content, tokenize = 'unicode61 remove_diacritics 2');");
Exec(c, "CREATE VIRTUAL TABLE FtsB USING fts5(Content, tokenize = 'trigram');");
Exec(c, "CREATE VIRTUAL TABLE FtsC USING fts5(Content, tokenize = 'unicode61 remove_diacritics 0');");
using var tx = c.BeginTransaction();
foreach (var s in samples)
{
foreach (var (table, text) in new[]
{
("FtsA", s.Text), ("FtsB", s.Text), ("FtsC", PrepareForIndex(s.Text))
})
{
using var cmd = c.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText = $"INSERT INTO {table}(rowid, Content) VALUES ($id, $t);";
cmd.Parameters.AddWithValue("$id", s.Id);
cmd.Parameters.AddWithValue("$t", text);
cmd.ExecuteNonQuery();
}
}
tx.Commit();
Console.WriteLine("=== PART 1: CORRECTNESS (OK = exact, EXTRA = found more, MISS/none = failed) ===");
Console.WriteLine($"{"Test",-24}{"Expected",-10}{"A: unicode61",-22}{"B: trigram",-22}{"C: normalized",-22}");
foreach (var t in tests)
{
var a = SearchIds(c, "FtsA", MethodQuery('A', t.Query));
var b = SearchIds(c, "FtsB", MethodQuery('B', t.Query));
var cc = SearchIds(c, "FtsC", MethodQuery('C', t.Query));
Console.WriteLine(
$"{t.Label,-24}{string.Join(",", t.Expected),-10}" +
$"{Describe(a, t.Expected),-22}{Describe(b, t.Expected),-22}{Describe(cc, t.Expected),-22}");
}
}
Console.WriteLine();
// =====================================================================
// PART 2: index size and speed on synthetic data
// =====================================================================
Console.WriteLine($"=== PART 2: SIZE AND SPEED ({SizeTestRows:N0} synthetic rows) ===");
Console.WriteLine("(Synthetic text repeats the same sentences, so use the ratios, not the absolute sizes.)");
var rnd = new Random(2027);
var rows = new string[SizeTestRows];
{
var sb = new StringBuilder();
for (int i = 0; i < rows.Length; i++)
{
sb.Clear();
int parts = rnd.Next(2, 40);
for (int p = 0; p < parts; p++)
{
if (p > 0) sb.Append(' ');
sb.Append(samples[rnd.Next(samples.Length)].Text);
}
rows[i] = sb.ToString();
}
}
var methods = new (char Method, string Tokenizer)[]
{
('A', "unicode61 remove_diacritics 2"),
('B', "trigram"),
('C', "unicode61 remove_diacritics 0"),
};
var speedQueries = new (string Label, string Query)[]
{
("zh 3 chars", "数据库"),
("ar word", "كتاب"),
("en word", "weather"),
};
foreach (var (method, tokenizer) in methods)
{
string file = $"fts_size_{method}.db";
DeleteDb(file);
var build = Stopwatch.StartNew();
using (var c = Open(file, password, fast: true))
{
// Contentless table: measures the size of the index only
Exec(c, $"CREATE VIRTUAL TABLE Idx USING fts5(Content, content = '', tokenize = '{tokenizer}');");
for (int start = 0; start < rows.Length; start += 20_000)
{
using var tx = c.BeginTransaction();
using var cmd = c.CreateCommand();
cmd.Transaction = tx;
cmd.CommandText = "INSERT INTO Idx(rowid, Content) VALUES ($id, $t);";
var pId = cmd.Parameters.Add("$id", SqliteType.Integer);
var pT = cmd.Parameters.Add("$t", SqliteType.Text);
int end = Math.Min(start + 20_000, rows.Length);
for (int i = start; i < end; i++)
{
pId.Value = i + 1;
pT.Value = method == 'C' ? PrepareForIndex(rows[i]) : rows[i];
cmd.ExecuteNonQuery();
}
tx.Commit();
}
Exec(c, "PRAGMA wal_checkpoint(TRUNCATE);");
}
build.Stop();
SqliteConnection.ClearAllPools();
double mb = new FileInfo(file).Length / 1024.0 / 1024.0;
Console.WriteLine();
Console.WriteLine($"Method {method} ({tokenizer}): file = {mb:F1} MB, build = {build.Elapsed.TotalSeconds:F1} s");
using var q = Open(file, password);
foreach (var sq in speedQueries)
{
string expr = MethodQuery(method, sq.Query);
double best = double.MaxValue;
int found = 0;
for (int run = 0; run < 3; run++)
{
var sw = Stopwatch.StartNew();
found = 0;
try
{
using var cmd = q.CreateCommand();
cmd.CommandText = "SELECT rowid FROM Idx WHERE Idx MATCH $q LIMIT 20;";
cmd.Parameters.AddWithValue("$q", expr);
using var r = cmd.ExecuteReader();
while (r.Read()) found++;
}
catch (SqliteException) { }
sw.Stop();
best = Math.Min(best, sw.Elapsed.TotalMilliseconds);
}
Console.WriteLine($" {sq.Label,-12} rows={found,-3} best={best,8:F2} ms");
}
}
DeleteDb(correctnessFile);
Console.WriteLine();
Console.WriteLine("Done.");
Correctness results
| Test | A: unicode61 | B: trigram | C: normalized |
|---|---|---|---|
| English word | OK | OK | OK |
| Arabic word without prefix | no result | partial | OK |
| Arabic word with al- | partial | partial | OK |
| Arabic alef variants | no result | no result | OK |
| Chinese, 3 characters | no result | OK | OK |
| Chinese, 2 characters | no result | no result | OK |
| Chinese, 2 characters (second word) | no result | no result | OK |
| Russian, lowercase query | OK | OK | OK |
| Russian, inflected form | OK | OK | OK |
| French, accents ignored | OK | no result | OK |
| French word | OK | OK | OK |
| Spanish word | OK | OK | OK |
Index size and speed (100,000 synthetic rows)
| Method | Index file size | Build time | Query time |
|---|---|---|---|
| A: unicode61 | 22.6 MB | 6.4 s | under 1 ms |
| B: trigram | 142.2 MB | 29.7 s | under 1 ms |
| C: normalized | 28.4 MB | 12.5 s | under 1 ms |
The synthetic text repeats the same sentences, so look at the ratios rather than the absolute sizes.
Takeaways
- Plain
unicode61is fine for English, French, Spanish and Russian, but not for Arabic or Chinese. It does not know about Arabic prefixes or letter variants, and it cannot split Chinese into words. - Trigram looks like an easy fix, but it is not. It made the index about six times larger, still failed on short Chinese queries and on accent-insensitive search, and did not solve the Arabic cases.
- Normalizing in the application (method C) won on every test and cost only about 25 percent more index space. The price is that you must apply the exact same normalization to every query.
- The Arabic article rule is a rough heuristic. It is a starting point, and you should test it with real text from your own domain.
5. Test 4: key wrapping, a recovery key and changing the password
The last test is about how to manage the encryption key properly. Using the password directly as the database key has two drawbacks: changing the password means re-encrypting the whole file, and a forgotten password means lost data. A better design separates the data key from the ways of unlocking it.
Master key (256 random bits) -> encrypts the SQLite file Secret key (256 random bits) -> encrypts selected rows with AES-GCM Both are stored "wrapped" (AES-GCM) in a small header file, vault.db.keys: - Master key wrapped by a key derived from the password (Argon2id, salt 1) - Secret key wrapped by a key derived from the password (Argon2id, salt 2) - Master key wrapped by a key derived from the recovery key (HKDF) - Secret key wrapped by a key derived from the recovery key (HKDF)
The consequences are what make this design attractive:
- Changing the password only re-wraps two small keys. The 3.5 GB database file is not touched at all, and the test proves it by hashing the file before and after.
- The recovery key is a second, independent way to unlock everything. It is 256 random bits shown as Base32 in groups of four characters, and it accepts lowercase letters and spaces when typed back.
- The secret key is not kept in memory after login. To read a protected row you type the password again, which runs Argon2id again and unwraps the secret key just for that operation.
- Every wrapped key is bound to its role and parameters through AES-GCM associated data, and every protected row is bound to its own id. Moving ciphertext from one row to another is detected.
- The database key is passed to SQLite as a 64-character hex string, which the library then processes with its own key derivation.
- Passwords are Unicode-normalized (NFKC) before hashing, so the same text typed on different keyboards gives the same key.
Argon2id settings used: 64 MB of memory, 3 iterations, 4 lanes. Measure the unlock time on your own hardware and tune these values.
Show the full program (about 450 lines)
using System.Diagnostics;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Konscious.Security.Cryptography;
using Microsoft.Data.Sqlite;
SQLitePCL.Batteries.Init();
const string dbPath = "vault.db";
const string password1 = "correct horse battery staple";
const string password2 = "a completely new password 2027";
const string secret1 = "the safe combination is 31-07-52";
const string secret2 = "account recovery phrase: tulip river window";
Vault.DeleteAll(dbPath);
int failures = 0;
void Check(string name, bool ok)
{
Console.WriteLine($"[{(ok ? "PASS" : "FAIL")}] {name}");
if (!ok) failures++;
}
static bool Rejected(Action action)
{
try { action(); return false; }
catch (CryptographicException) { return true; }
catch (FormatException) { return true; }
catch (SqliteException) { return true; }
catch (ArgumentException) { return true; }
}
static bool ContainsBytes(byte[] haystack, string needle) =>
haystack.AsSpan().IndexOf(new ReadOnlySpan<byte>(Encoding.UTF8.GetBytes(needle))) >= 0;
long CountItems(byte[] key)
{
using var conn = Vault.OpenDb(dbPath, key);
return Vault.Scalar<long>(conn, "SELECT COUNT(*) FROM Item;");
}
// ------------------------------------------------------------------
Console.WriteLine("=== 1. CREATE VAULT ===");
var sw = Stopwatch.StartNew();
string recoveryKey = Vault.Create(dbPath, password1);
Console.WriteLine($"Created in {sw.ElapsedMilliseconds} ms (two Argon2id runs)");
Console.WriteLine("Recovery key (an application would show it once): " + recoveryKey);
Check("database file exists", File.Exists(dbPath));
Check("key header file exists", File.Exists(dbPath + ".keys"));
var master = Vault.UnlockMasterWithPassword(dbPath, password1);
using (var dbSeed = Vault.OpenDb(dbPath, master))
Vault.Exec(dbSeed, "INSERT INTO Item (Content) VALUES ('ordinary row about database design');");
CryptographicOperations.ZeroMemory(master);
Console.WriteLine();
// ------------------------------------------------------------------
Console.WriteLine("=== 2. UNLOCK WITH PASSWORD ===");
sw.Restart();
master = Vault.UnlockMasterWithPassword(dbPath, password1);
Console.WriteLine($"Unlock time (Argon2id + open): {sw.ElapsedMilliseconds} ms");
Check("correct password opens the database", CountItems(master) == 1);
CryptographicOperations.ZeroMemory(master);
Check("wrong password is rejected",
Rejected(() => Vault.UnlockMasterWithPassword(dbPath, "wrong password")));
Check("empty password is rejected",
Rejected(() => Vault.UnlockMasterWithPassword(dbPath, "")));
Check("typing the password straight into SQLite is rejected",
Rejected(() =>
{
using var conn = Vault.OpenDbText(dbPath, password1);
Vault.Scalar<long>(conn, "SELECT COUNT(*) FROM Item;");
}));
Check("a random key is rejected",
Rejected(() =>
{
using var conn = Vault.OpenDb(dbPath, RandomNumberGenerator.GetBytes(32));
Vault.Scalar<long>(conn, "SELECT COUNT(*) FROM Item;");
}));
Console.WriteLine();
// ------------------------------------------------------------------
Console.WriteLine("=== 3. UNLOCK WITH RECOVERY KEY ===");
master = Vault.UnlockMasterWithRecovery(dbPath, recoveryKey);
Check("recovery key opens the database", CountItems(master) == 1);
CryptographicOperations.ZeroMemory(master);
string sloppy = recoveryKey.ToLowerInvariant().Replace('-', ' ');
master = Vault.UnlockMasterWithRecovery(dbPath, sloppy);
Check("recovery key typed in lowercase with spaces still works", CountItems(master) == 1);
CryptographicOperations.ZeroMemory(master);
string wrongRecovery = (recoveryKey[0] == 'A' ? "B" : "A") + recoveryKey.Substring(1);
Check("a wrong recovery key is rejected",
Rejected(() => Vault.UnlockMasterWithRecovery(dbPath, wrongRecovery)));
Check("a malformed recovery key is rejected",
Rejected(() => Vault.UnlockMasterWithRecovery(dbPath, "not-a-key-1")));
Console.WriteLine();
// ------------------------------------------------------------------
Console.WriteLine("=== 4. SECRET ROWS (second encryption layer) ===");
var secretKey = Vault.UnlockSecretWithPassword(dbPath, password1); // password typed again
master = Vault.UnlockMasterWithPassword(dbPath, password1);
long secretId1, secretId2;
byte[] cipher1, cipher2;
using (var dbSecret = Vault.OpenDb(dbPath, master))
{
secretId1 = Vault.AddSecret(dbSecret, secretKey, secret1);
secretId2 = Vault.AddSecret(dbSecret, secretKey, secret2);
cipher1 = Vault.ReadCipher(dbSecret, secretId1);
cipher2 = Vault.ReadCipher(dbSecret, secretId2);
}
Check("secret text is not readable even with the database key",
!ContainsBytes(cipher1, "safe combination") && !ContainsBytes(cipher2, "tulip"));
CryptographicOperations.ZeroMemory(secretKey);
Check("raw database file does not contain the ordinary row",
!ContainsBytes(File.ReadAllBytes(dbPath), "ordinary row"));
Check("wrong password cannot unlock the secret key",
Rejected(() => Vault.UnlockSecretWithPassword(dbPath, "wrong password")));
secretKey = Vault.UnlockSecretWithPassword(dbPath, password1);
using (var dbRead = Vault.OpenDb(dbPath, master))
{
Check("secret row decrypts after typing the password again",
Vault.ReadSecret(dbRead, secretKey, secretId1) == secret1);
var tampered = (byte[])cipher1.Clone();
tampered[20] ^= 0x01;
Vault.WriteCipher(dbRead, secretId1, tampered);
Check("a single flipped bit is detected",
Rejected(() => Vault.ReadSecret(dbRead, secretKey, secretId1)));
Vault.WriteCipher(dbRead, secretId1, cipher1);
Vault.WriteCipher(dbRead, secretId2, cipher1);
Check("ciphertext moved to another row is detected",
Rejected(() => Vault.ReadSecret(dbRead, secretKey, secretId2)));
Vault.WriteCipher(dbRead, secretId2, cipher2);
Check("both rows decrypt again after restoring",
Vault.ReadSecret(dbRead, secretKey, secretId1) == secret1 &&
Vault.ReadSecret(dbRead, secretKey, secretId2) == secret2);
}
CryptographicOperations.ZeroMemory(secretKey);
secretKey = Vault.UnlockSecretWithRecovery(dbPath, recoveryKey);
using (var dbRec = Vault.OpenDb(dbPath, master))
Check("recovery key also opens the secret rows",
Vault.ReadSecret(dbRec, secretKey, secretId2) == secret2);
CryptographicOperations.ZeroMemory(secretKey);
CryptographicOperations.ZeroMemory(master);
Console.WriteLine();
// ------------------------------------------------------------------
Console.WriteLine("=== 5. CHANGE PASSWORD ===");
string hashBefore = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(dbPath)));
sw.Restart();
Vault.ChangePassword(dbPath, password1, password2);
Console.WriteLine($"Password change time: {sw.ElapsedMilliseconds} ms");
string hashAfter = Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(dbPath)));
Check("database file is byte-for-byte unchanged", hashBefore == hashAfter);
Check("old password is rejected",
Rejected(() => Vault.UnlockMasterWithPassword(dbPath, password1)));
Check("old password is rejected for the secret key",
Rejected(() => Vault.UnlockSecretWithPassword(dbPath, password1)));
master = Vault.UnlockMasterWithPassword(dbPath, password2);
Check("new password opens the database", CountItems(master) == 1);
CryptographicOperations.ZeroMemory(master);
master = Vault.UnlockMasterWithRecovery(dbPath, recoveryKey);
Check("recovery key still works after the change", CountItems(master) == 1);
secretKey = Vault.UnlockSecretWithPassword(dbPath, password2);
using (var dbAfter = Vault.OpenDb(dbPath, master))
Check("secret rows open with the new password",
Vault.ReadSecret(dbAfter, secretKey, secretId1) == secret1);
CryptographicOperations.ZeroMemory(secretKey);
CryptographicOperations.ZeroMemory(master);
Console.WriteLine();
Console.WriteLine(failures == 0 ? "ALL CHECKS PASSED" : $"{failures} CHECK(S) FAILED");
Vault.DeleteAll(dbPath);
// ==================================================================
// Types (must come after the top-level statements)
// ==================================================================
class KeyHeader
{
public int Version { get; set; } = 1;
public int MemoryKb { get; set; }
public int Iterations { get; set; }
public int Parallelism { get; set; }
public byte[] PasswordSalt { get; set; } = Array.Empty<byte>();
public byte[] SecretSalt { get; set; } = Array.Empty<byte>();
public byte[] RecoverySalt { get; set; } = Array.Empty<byte>();
public byte[] MasterByPassword { get; set; } = Array.Empty<byte>();
public byte[] SecretByPassword { get; set; } = Array.Empty<byte>();
public byte[] MasterByRecovery { get; set; } = Array.Empty<byte>();
public byte[] SecretByRecovery { get; set; } = Array.Empty<byte>();
}
static class Vault
{
const int KeyBytes = 32;
const int DefaultMemoryKb = 65536; // 64 MB
const int DefaultIterations = 3;
const int DefaultParallelism = 4;
static readonly JsonSerializerOptions JsonOptions = new() { WriteIndented = true };
// ---------- File handling ----------
static string HeaderPath(string dbPath) => dbPath + ".keys";
public static void DeleteAll(string dbPath)
{
foreach (var f in new[]
{
dbPath, dbPath + "-journal", dbPath + "-wal", dbPath + "-shm",
HeaderPath(dbPath), HeaderPath(dbPath) + ".tmp"
})
if (File.Exists(f)) File.Delete(f);
}
static KeyHeader ReadHeader(string dbPath) =>
JsonSerializer.Deserialize<KeyHeader>(File.ReadAllText(HeaderPath(dbPath)))
?? throw new InvalidDataException("Key header is empty or corrupt.");
static void WriteHeader(string dbPath, KeyHeader h)
{
// Write to a temp file, then replace: a crash cannot leave a half-written header
string path = HeaderPath(dbPath);
string tmp = path + ".tmp";
File.WriteAllText(tmp, JsonSerializer.Serialize(h, JsonOptions));
File.Move(tmp, path, overwrite: true);
}
// ---------- Database ----------
public static SqliteConnection OpenDb(string dbPath, byte[] masterKey) =>
OpenDbText(dbPath, Convert.ToHexString(masterKey));
public static SqliteConnection OpenDbText(string dbPath, string keyText)
{
var cs = new SqliteConnectionStringBuilder
{
DataSource = dbPath,
Password = keyText,
Pooling = false // no pooled handles keeping the file locked
}.ToString();
var conn = new SqliteConnection(cs);
conn.Open();
return conn;
}
public static void Exec(SqliteConnection c, string sql)
{
using var cmd = c.CreateCommand();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
public static T Scalar<T>(SqliteConnection c, string sql)
{
using var cmd = c.CreateCommand();
cmd.CommandText = sql;
return (T)Convert.ChangeType(cmd.ExecuteScalar()!, typeof(T));
}
// ---------- Create ----------
public static string Create(string dbPath, string password)
{
if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password is empty.");
var master = RandomNumberGenerator.GetBytes(KeyBytes);
var secret = RandomNumberGenerator.GetBytes(KeyBytes);
var recovery = RandomNumberGenerator.GetBytes(KeyBytes);
var h = new KeyHeader
{
MemoryKb = DefaultMemoryKb,
Iterations = DefaultIterations,
Parallelism = DefaultParallelism,
PasswordSalt = RandomNumberGenerator.GetBytes(16),
SecretSalt = RandomNumberGenerator.GetBytes(16),
RecoverySalt = RandomNumberGenerator.GetBytes(16)
};
var kekMain = DeriveFromPassword(password, h.PasswordSalt, h);
var kekSecret = DeriveFromPassword(password, h.SecretSalt, h);
var kekRecMain = DeriveFromRecovery(recovery, h.RecoverySalt, "main");
var kekRecSecret = DeriveFromRecovery(recovery, h.RecoverySalt, "secret");
h.MasterByPassword = Seal(kekMain, master, PwAad("main-pw", h, h.PasswordSalt));
h.SecretByPassword = Seal(kekSecret, secret, PwAad("secret-pw", h, h.SecretSalt));
h.MasterByRecovery = Seal(kekRecMain, master, RecAad("main-rec", h));
h.SecretByRecovery = Seal(kekRecSecret, secret, RecAad("secret-rec", h));
WriteHeader(dbPath, h);
using (var conn = OpenDb(dbPath, master))
{
Exec(conn, "CREATE TABLE Item (Id INTEGER PRIMARY KEY, Content TEXT NOT NULL);");
Exec(conn, "CREATE TABLE SecretItem (" +
"Id INTEGER PRIMARY KEY, CreatedAt INTEGER NOT NULL, Cipher BLOB NOT NULL);");
}
string recoveryText = FormatRecovery(recovery);
Zero(master, secret, recovery, kekMain, kekSecret, kekRecMain, kekRecSecret);
return recoveryText;
}
// ---------- Unlock ----------
public static byte[] UnlockMasterWithPassword(string dbPath, string password)
{
var h = ReadHeader(dbPath);
var kek = DeriveFromPassword(password, h.PasswordSalt, h);
try { return Unseal(kek, h.MasterByPassword, PwAad("main-pw", h, h.PasswordSalt)); }
finally { Zero(kek); }
}
public static byte[] UnlockSecretWithPassword(string dbPath, string password)
{
var h = ReadHeader(dbPath);
var kek = DeriveFromPassword(password, h.SecretSalt, h);
try { return Unseal(kek, h.SecretByPassword, PwAad("secret-pw", h, h.SecretSalt)); }
finally { Zero(kek); }
}
public static byte[] UnlockMasterWithRecovery(string dbPath, string recoveryText)
{
var h = ReadHeader(dbPath);
var recovery = ParseRecovery(recoveryText);
var kek = DeriveFromRecovery(recovery, h.RecoverySalt, "main");
try { return Unseal(kek, h.MasterByRecovery, RecAad("main-rec", h)); }
finally { Zero(kek, recovery); }
}
public static byte[] UnlockSecretWithRecovery(string dbPath, string recoveryText)
{
var h = ReadHeader(dbPath);
var recovery = ParseRecovery(recoveryText);
var kek = DeriveFromRecovery(recovery, h.RecoverySalt, "secret");
try { return Unseal(kek, h.SecretByRecovery, RecAad("secret-rec", h)); }
finally { Zero(kek, recovery); }
}
// ---------- Change password (the database file is NOT touched) ----------
public static void ChangePassword(string dbPath, string oldPassword, string newPassword)
{
if (string.IsNullOrEmpty(newPassword)) throw new ArgumentException("New password is empty.");
var master = UnlockMasterWithPassword(dbPath, oldPassword);
var secret = UnlockSecretWithPassword(dbPath, oldPassword);
var h = ReadHeader(dbPath);
h.PasswordSalt = RandomNumberGenerator.GetBytes(16);
h.SecretSalt = RandomNumberGenerator.GetBytes(16);
var kekMain = DeriveFromPassword(newPassword, h.PasswordSalt, h);
var kekSecret = DeriveFromPassword(newPassword, h.SecretSalt, h);
h.MasterByPassword = Seal(kekMain, master, PwAad("main-pw", h, h.PasswordSalt));
h.SecretByPassword = Seal(kekSecret, secret, PwAad("secret-pw", h, h.SecretSalt));
WriteHeader(dbPath, h);
Zero(master, secret, kekMain, kekSecret);
}
// ---------- Secret rows ----------
static byte[] RowAad(long id) => Encoding.UTF8.GetBytes($"vault|secret-item|{id}");
public static long AddSecret(SqliteConnection c, byte[] secretKey, string text)
{
using var tx = c.BeginTransaction();
long id;
using (var cmd = c.CreateCommand())
{
cmd.Transaction = tx;
cmd.CommandText = "SELECT IFNULL(MAX(Id), 0) + 1 FROM SecretItem;";
id = Convert.ToInt64(cmd.ExecuteScalar());
}
var cipher = Seal(secretKey, Encoding.UTF8.GetBytes(text), RowAad(id));
using (var cmd = c.CreateCommand())
{
cmd.Transaction = tx;
cmd.CommandText = "INSERT INTO SecretItem (Id, CreatedAt, Cipher) VALUES ($id, $d, $c);";
cmd.Parameters.AddWithValue("$id", id);
cmd.Parameters.AddWithValue("$d", DateTimeOffset.UtcNow.ToUnixTimeSeconds());
cmd.Parameters.AddWithValue("$c", cipher);
cmd.ExecuteNonQuery();
}
tx.Commit();
return id;
}
public static byte[] ReadCipher(SqliteConnection c, long id)
{
using var cmd = c.CreateCommand();
cmd.CommandText = "SELECT Cipher FROM SecretItem WHERE Id = $id;";
cmd.Parameters.AddWithValue("$id", id);
return (byte[])cmd.ExecuteScalar()!;
}
public static void WriteCipher(SqliteConnection c, long id, byte[] cipher)
{
using var cmd = c.CreateCommand();
cmd.CommandText = "UPDATE SecretItem SET Cipher = $c WHERE Id = $id;";
cmd.Parameters.AddWithValue("$c", cipher);
cmd.Parameters.AddWithValue("$id", id);
cmd.ExecuteNonQuery();
}
public static string ReadSecret(SqliteConnection c, byte[] secretKey, long id) =>
Encoding.UTF8.GetString(Unseal(secretKey, ReadCipher(c, id), RowAad(id)));
// ---------- Key derivation ----------
static byte[] DeriveFromPassword(string password, byte[] salt, KeyHeader h)
{
if (string.IsNullOrEmpty(password)) throw new ArgumentException("Password is empty.");
var pw = Encoding.UTF8.GetBytes(password.Normalize(NormalizationForm.FormKC));
try
{
using var argon = new Argon2id(pw)
{
Salt = salt,
MemorySize = h.MemoryKb,
Iterations = h.Iterations,
DegreeOfParallelism = h.Parallelism
};
return argon.GetBytes(KeyBytes);
}
finally { CryptographicOperations.ZeroMemory(pw); }
}
// The recovery key is already 256 random bits, so HKDF is enough (no slow hashing needed)
static byte[] DeriveFromRecovery(byte[] recovery, byte[] salt, string purpose) =>
HKDF.DeriveKey(HashAlgorithmName.SHA256, recovery, KeyBytes, salt,
Encoding.UTF8.GetBytes("vault-recovery-" + purpose));
// Associated data binds every wrapped key to its role and parameters
static byte[] PwAad(string label, KeyHeader h, byte[] salt) =>
Encoding.UTF8.GetBytes(
$"vault|v{h.Version}|{label}|{h.MemoryKb}|{h.Iterations}|{h.Parallelism}|{Convert.ToBase64String(salt)}");
static byte[] RecAad(string label, KeyHeader h) =>
Encoding.UTF8.GetBytes($"vault|v{h.Version}|{label}|{Convert.ToBase64String(h.RecoverySalt)}");
// ---------- AES-256-GCM (blob = nonce[12] + ciphertext + tag[16]) ----------
static byte[] Seal(byte[] key, byte[] plaintext, byte[] aad)
{
var nonce = RandomNumberGenerator.GetBytes(12);
var cipher = new byte[plaintext.Length];
var tag = new byte[16];
using var aes = new AesGcm(key, 16);
aes.Encrypt(nonce, plaintext, cipher, tag, aad);
var blob = new byte[12 + cipher.Length + 16];
nonce.CopyTo(blob, 0);
cipher.CopyTo(blob, 12);
tag.CopyTo(blob, 12 + cipher.Length);
return blob;
}
static byte[] Unseal(byte[] key, byte[] blob, byte[] aad)
{
if (blob.Length < 28) throw new CryptographicException("Encrypted blob is too short.");
var nonce = blob.AsSpan(0, 12);
var cipher = blob.AsSpan(12, blob.Length - 28);
var tag = blob.AsSpan(blob.Length - 16, 16);
var plain = new byte[cipher.Length];
using var aes = new AesGcm(key, 16);
aes.Decrypt(nonce, cipher, tag, plain, aad); // throws if key, data or context is wrong
return plain;
}
// ---------- Recovery key text (Base32, groups of 4) ----------
const string Base32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
static string FormatRecovery(byte[] key)
{
var raw = Base32Encode(key);
var groups = new List<string>();
for (int i = 0; i < raw.Length; i += 4)
groups.Add(raw.Substring(i, Math.Min(4, raw.Length - i)));
return string.Join('-', groups);
}
static byte[] ParseRecovery(string text)
{
var key = Base32Decode(text);
if (key.Length != KeyBytes) throw new FormatException("Recovery key has the wrong length.");
return key;
}
static string Base32Encode(byte[] data)
{
var sb = new StringBuilder();
int buffer = 0, bits = 0;
foreach (var b in data)
{
buffer = (buffer << 8) | b;
bits += 8;
while (bits >= 5)
{
sb.Append(Base32Alphabet[(buffer >> (bits - 5)) & 31]);
bits -= 5;
}
buffer &= (1 << bits) - 1;
}
if (bits > 0) sb.Append(Base32Alphabet[(buffer << (5 - bits)) & 31]);
return sb.ToString();
}
static byte[] Base32Decode(string text)
{
var clean = new string(text.Where(ch => ch != '-' && !char.IsWhiteSpace(ch)).ToArray())
.ToUpperInvariant();
var output = new List<byte>();
int buffer = 0, bits = 0;
foreach (var ch in clean)
{
int v = Base32Alphabet.IndexOf(ch);
if (v < 0) throw new FormatException("Invalid character in recovery key.");
buffer = (buffer << 5) | v;
bits += 5;
if (bits >= 8)
{
output.Add((byte)((buffer >> (bits - 8)) & 0xFF));
bits -= 8;
}
buffer &= (1 << bits) - 1;
}
return output.ToArray();
}
static void Zero(params byte[][] arrays)
{
foreach (var a in arrays) CryptographicOperations.ZeroMemory(a);
}
}
What the program checks
The program prints [PASS] or [FAIL] for each check and a final summary line. The checks cover:
| Check | Threat it covers |
|---|---|
| Wrong, empty and raw passwords; a random key | Guessing the password or key |
| Recovery key: correct, typed sloppily, wrong, malformed | Usability without weakening security |
| Protected rows are unreadable even with the database key | A stolen file plus a stolen session key |
| One flipped bit in a ciphertext is detected | Tampering |
| Ciphertext moved to another row is detected | Substitution attacks |
| Database file is byte-for-byte identical after a password change | No full re-encryption needed |
| Old password rejected, new password and recovery key work | Correct password rotation |
Honest limitations
- The header file is a single point of failure. The database cannot be opened without it, even with the right password. Back up the database and the header together, and keep a second copy of the header somewhere else.
- There is no lockout on repeated wrong passwords. Argon2id makes every guess expensive, but a real application should add its own delay. This does not stop an attacker who holds both files and runs their own tool against them, so a strong password still matters most.
- The key lives in memory while the program runs. Malware on the same machine can read it. Zeroing buffers after use and locking after a period of inactivity reduce the exposure, but do not remove it.
- This is an experiment, not an audited design. Have anything that protects real data reviewed before you rely on it.
6. Troubleshooting: everything that broke
| Symptom | Cause and fix |
|---|---|
CS0234: The type or namespace name 'Batteries_V2' does not exist in the namespace 'SQLitePCL' | With the current packages, initialize with SQLitePCL.Batteries.Init(); instead of Batteries_V2.Init(). |
| NuGet shows SQLitePCLRaw.bundle_e_sqlite3mc as deprecated ("legacy and no longer maintained") | Use SQLite3MC.PCLRaw.bundle instead, which is published under the SQLite3 Multiple Ciphers project. |
The restore log says the bundle was installed, but dotnet list package does not list it | The package was not saved in the project file. Run dotnet add package SQLite3MC.PCLRaw.bundle again from the project folder and check with dotnet list package. |
| Restore errors about package versions or conflicts | Make sure only Microsoft.Data.Sqlite.Core and one bundle are referenced. dotnet nuget locals all --clear followed by dotnet restore clears stale caches. |
IOException: The process cannot access the file ... because it is being used by another process | Connection pooling keeps the file open. Call SqliteConnection.ClearAllPools() or set Pooling = false. |
IOException: The file is too long. This operation is currently limited to supporting files less than 2 gigabytes | File.ReadAllBytes cannot read files over 2 GB. The benchmark scans the file in chunks instead. |
FileLoadException ... An Application Control policy has blocked this file. (0x800711C7) | See the next section. |
The "Application Control policy has blocked this file" error
This one is not a firewall problem, and it is not about your code. On Windows 11 it is usually Smart App Control, which blocks any unsigned program, including the DLLs you build yourself, so it hits every project. You can check it under Windows Security, App & browser control, Smart App Control settings. If it is set to On, that is your cause.
- Turning it Off and restarting fixes it. Read what Windows tells you before you do this: on many builds it is a one-way switch that cannot be turned back on without reinstalling Windows. Microsoft Defender keeps protecting the machine either way.
- If you would rather not turn it off, develop inside a virtual machine or another computer.
- If the machine is managed by an employer, the block may come from a WDAC or AppLocker policy instead. In that case ask your IT department for an exception rather than trying to bypass it.
- Code signing with a self-signed certificate does not help, because the feature only trusts certificates from trus
No comments:
Post a Comment
Note: only a member of this blog may post a comment.