无法在SQLite的Connection String中提供密码

Tsc*_*eck 4 c# sqlite entity-framework entity-framework-core

我使用SQLite和Entity Framework.

我使用以下代码创建数据库:

class MyContext : DbContext
{   
    // DbSets, OnModelCreating(), etc.

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=c:\\test.db");
    }
}

//this is in my test method
 using (var db = new MyContext())
{
    db.Database.EnsureCreated();
}
Run Code Online (Sandbox Code Playgroud)

上面的代码有效.数据库被创建.但我想通过在连接字符串中提供密码来加密数据库:

optionsBuilder.UseSqlite("Data Source=c:\\test.db;Password=mypassword");
Run Code Online (Sandbox Code Playgroud)

在这种情况下,在EnsureCreated调用之后,我得到了异常

System.Data.dll中发生未处理的"System.ArgumentException"类型异常附加信息:不支持关键字:"password".

使用密码有什么问题?如何加密SQLite数据库?

Tsc*_*eck 6

"纯"的开源sqlite3.dll不支持加密.还有其他实现,包括许可和未许可.对于我的解决方案,我使用了GitHub的rindeal/SQLite3-Encryption项目

我的解决方案

  1. 下载编译的二进制文件
  2. 将sqlite3.dll复制到BIN文件夹
    • 将DLL添加到Visual Studio中的项目
    • 将复制设置为输出目录 - 始终复制
  3. 在上下文的构造函数中使用此代码:

    string password;
    var connection = Database.GetDbConnection();
    connection.Open();
    using (var command = connection.CreateCommand())
    {
        command.CommandText = $"PRAGMA key='{password}';";
        command.ExecuteNonQuery();
    }
    
    Run Code Online (Sandbox Code Playgroud)


Nko*_*osi 3

根据这个答案保护 EntityFramework Core Application 使用的 SQLite 数据库

EF Core 使用 Microsoft.Data.Sqlite,目前不支持开箱即用的加密。请参阅 https://github.com/aspnet/Microsoft.Data.Sqlite/issues/184。您可以使用 SQLite 扩展自行添加加密。

在提供的 GitHub 链接中,还有其他替代方案的链接:

Microsoft.Data.Sqlite 中的加密