Protect an SQLite database in an UWP app

2019-09-03 13:09发布

问题:

It is an UWPapplication using a SQLite database. Below, the dependencies for this application:

{
    "dependencies": {
    "Microsoft.EntityFrameworkCore.Sqlite": "1.0.1",
    "Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final",
    "Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2",
    "Microsoft.Xaml.Behaviors.Uwp.Managed": "1.1.0",
    "Newtonsoft.Json": "8.0.3",
    "Template10": "1.1.*"
    },
    // ...
}

The requirement is: "[...]to have a password to access the database either from the application or any other application that can open a SQLite database".

Entity Framework Core doesn't seem to support this scenario. Any suggestion?

回答1:

See my Encryption in Microsoft.Data.Sqlite post for tips on using SQLCipher and friends with Microsoft.Data.Sqlite.

The easiest way to use it with EF Core is probably to use an open connection with your DbContext.

class MyContext : DbContext
{
    SqliteConnection _connection;

    protected override void OnConfiguring(DbContextOptionsBuilder options)
    {
        _connection = new SqliteConnection(_connectionString);
        _connection.Open();

        var command = _connection.CreateCommand();
        command.CommandText = "PRAGMA key = 'password';";
        command.ExecuteNonQuery();

        options.UseSqlite(_connection);
    }

    protected override void Dispose()
    {
        _connection?.Dispose();
    }
}


回答2:

Take a look at SQLCipher (https://github.com/sqlcipher/sqlcipher). It provides seamless full DB encryption with little overhead. It is a pain to build a VSIX for use with Visual Studio. If you do not want to build it yourself, yo can get a license from https://www.zetetic.net/sqlcipher/.