SQLCipher .NET with Entity Core - 设置或删除密码

SQLCipher .NET with Entity Core - set or remove password

我正在使用 SQLCipher(社区版)运行.NET 和 Entity Core。一切正常,包括更改现有数据库的密码。

例如,如果 DB 使用密码“1”进行保护,则可以将其更改(重新加密)为“2”或其他任何内容。但是,当我想保护未受保护的数据库或从有密码的数据库中删除保护时会出现问题。

目前更改数据库密码的代码如下所示:

public bool Rekey(string oldKey, string newKey)
    {
        SqliteConnection conn = GetConnection(oldKey);

        try
        {
            conn.Open();
            using (var command = conn.CreateCommand())
            {
                command.CommandText = $"PRAGMA rekey = '{newKey}';";
                int rowsChanged = command.ExecuteNonQuery();
            }
            conn.Close();
        }
        catch
        {
            return false;
        }
        return true;
    }

private SqliteConnection GetConnection(string key)
    {
        SqliteConnection conn;
        if (_dbaccessBytes == null)
        {
            conn = new SqliteConnection
            {
                ConnectionString = new SqliteConnectionStringBuilder()
                {
                    DataSource = _databasePath,
                    Mode = SqliteOpenMode.ReadWriteCreate
                }.ToString()
            };
        }
        else
        {
            conn = new SqliteConnection
            {
                ConnectionString = new SqliteConnectionStringBuilder()
                {
                    DataSource = _databasePath,
                    Mode = SqliteOpenMode.ReadWriteCreate,
                    Password = key
                }.ToString()
            };
        }

        return conn;
    }

因此,当我们没有密码保护并且将 oldKey 作为 NULL 发送并将 newKey 作为某个值发送时 - 它只会 运行,但不会设置密码。没有错误。 我试图查找解决方案,但还没有运气。可能是我缺少一些理解,设置和删除密钥应该不像 'PRAGMA rekey' 那样完成,而是用其他方法?

提前致谢。

'PRAGMA rekey' 用于更改数据库的现有密码。要为未加密的数据库设置密码或将其从受密码保护的数据库中删除,应使用 sqlcipher_export() 函数。 这在 SQLCipher 文档 here.

中有描述

也许有人会发现代码示例很有用。要解密数据库,您应该建立连接,如:

SqliteConnection conn = GetConnection();
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"ATTACH DATABASE '{newDBPath}' AS plaintext KEY '';";
command.ExecuteNonQuery();
command.CommandText = @"SELECT sqlcipher_export('plaintext');";
command.ExecuteNonQuery();
command.CommandText = @"DETACH DATABASE plaintext;";
command.ExecuteNonQuery();

因此,对于加密你应该做类似的事情:

SqliteConnection conn = GetConnection();
conn.Open();
using var command = conn.CreateCommand();
command.CommandText = $"ATTACH DATABASE '{newDBPath}' AS encrypted KEY '{newKey}';";
command.ExecuteNonQuery();
command.CommandText = @"SELECT sqlcipher_export('encrypted');";
command.ExecuteNonQuery();
command.CommandText = @"DETACH DATABASE encrypted;";
command.ExecuteNonQuery();