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

时间:2016-06-16 13:37:13

标签: c# entity-framework sqlite 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();
}

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

optionsBuilder.UseSqlite("Data Source=c:\\test.db;Password=mypassword");

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

  

System.Data.dll中发生了未处理的“System.ArgumentException”类型异常   其他信息:不支持关键字:'密码'。

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

4 个答案:

答案 0 :(得分:6)

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

我的解决方案:

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

答案 1 :(得分:2)

根据这个答案Protect SQLite database used by EntityFramework Core Application

  

EF Core使用目前不支持的Microsoft.Data.Sqlite   加密开箱即用。看到   https://github.com/aspnet/Microsoft.Data.Sqlite/issues/184。你可以   使用SQLite扩展自己添加加密。

在提供的GitHub链接中,还有其他链接指向

Encryption in Microsoft.Data.Sqlite

答案 2 :(得分:1)

我找到了一个不涉及在BIN文件夹中复制dll的解决方案。

看看it

答案 3 :(得分:0)

我已经使用了Tschareck发布的实现:

 private const string Password = "1234";
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            var conn = new SqliteConnection(@"Data Source=test.db;");
            conn.Open();

            using (var command = conn.CreateCommand())
            {
                command.CommandText = $"PRAGMA key = '{Password}';";
                command.ExecuteNonQuery();
            }
            optionsBuilder.UseSqlite(conn);
        }

并设法将密码输入我的解决方案,解决方案正常,但我有另一个问题 - 我无法使用该密码打开数据库(我使用DB Browser for SQL Lite)(当我点击&#时34;确定"密码被删除,没有任何反应):

printScreen DB Browser