SQLCipher.NET与实体核心-设置或删除密码



我使用的是运行的SQLCipher(社区版(。NET和实体核心。一切都很完美,包括更改现有数据库上的密码。

例如,如果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文档对此进行了描述。

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

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

最新更新