Encrypt SQLite database in C#

Posted on

Problem :

What is the best approach to encrypting a SQLite database file in .Net/C#? I’m using sqlite-dotnet2 wrapper.

There are tools like SQLite Encryption Extension and SQLite Crypt, but both are non-free, while my project is under GPL.

The naive approach I thought of using was to let SQLite handle a temporary file, then to encrypt it on program exit, and overwrite (zero-out) the original. The obvious drawback is that if program crashes (and while it is running), the plain text DB is accessible.

Is there a better way to approach this? Can I pass an encrypted stream to the wrapper (instead of using SQLiteConnection.CreateFile) ?

[edit] Maybe I am overthinking this. Is is sufficient to use Password option in the connection string? Would the file be encrypted properly in that case (or is it some weaker protection)?

Solution :

I recommend using the System.Data.Sqlite wrapper, which includes encryption. It works great, it’s easy to use, and it’s a complete ADO.Net implementation. You can get the wrapper from https://system.data.sqlite.org, and the developer describes how to use the encryption on this forum at: https://web.archive.org/web/20100207030625/http://sqlite.phxsoftware.com/forums/t/130.aspx. Hint – you just set the password property. He also describes how he does the encryption using the Microsoft Crypto API elsewhere in the forum.

Take a look at:


It is open source.

You can chek also the code for the wxsqlite3.

I would try http://code.google.com/p/csharp-sqlite/, it’s rewrite of SQLite 3.6.16 in C#, under MIT License. I suppose it will be easy to tweak it.

EDIT: As mentioned in the note below, it also support sqlcipher encryption

UPDATE: Since Google Code went read only the project has moved to it’s own website https://system.data.sqlite.org/index.html/doc/trunk/www/index.wiki

Leave a Reply

Your email address will not be published. Required fields are marked *