C# 向Xamarin表单中的Sqlite文件添加密码
我有一个Xamarin表单应用程序,它创建了一个Sqlite数据库C# 向Xamarin表单中的Sqlite文件添加密码,c#,sqlite,xamarin.forms,entity-framework-core,C#,Sqlite,Xamarin.forms,Entity Framework Core,我有一个Xamarin表单应用程序,它创建了一个Sqlite数据库 Microsoft.EntityFrameworkCore.Sqlite用于创建数据库。我想向文件中添加密码。我在网上搜索过,但不幸的是我找不到任何明显的方法。关于StackOverflow,有一些问题与我的问题类似,但是,平台不是Xamarin Forms 以下是问题: 这是我创建数据库的代码: public class DoctorDatabaseContext : DbContext { priva
Microsoft.EntityFrameworkCore.Sqlite
用于创建数据库。我想向文件中添加密码。我在网上搜索过,但不幸的是我找不到任何明显的方法。关于StackOverflow,有一些问题与我的问题类似,但是,平台不是Xamarin Forms
以下是问题:
public class DoctorDatabaseContext : DbContext
{
private readonly string DatabasePath;
public virtual DbSet<OperationsNames> OperationsNames { get; set; }
public virtual DbSet<CommonChiefComplaint> CommonChiefComplaint { get; set; }
public virtual DbSet<CommonDiagnosis> CommonDiagnosis { get; set; }
public virtual DbSet<CommonLabTests> CommonLabTests { get; set; }
public DoctorDatabaseContext(string DatabasePath)
{
FixedDatabasePath.Path = this.DatabasePath = DatabasePath;
Database.EnsureCreated();
}
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite($"Filename={DatabasePath}");
}
}
公共类DoctorDatabaseContext:DbContext
{
私有只读字符串数据库路径;
公共虚拟数据库集操作名称{get;set;}
公共虚拟数据库集CommonChiefComplaint{get;set;}
公共虚拟数据库集CommonDiagnosis{get;set;}
公共虚拟数据库集CommonLabTests{get;set;}
公共DoctorDatabaseContext(字符串数据库路径)
{
FixedDatabasePath.Path=this.DatabasePath=DatabasePath;
数据库。请重新创建();
}
配置时受保护的覆盖无效(DBContextOptions Builder Options Builder)
{
optionsBuilder.UseSqlite($“Filename={DatabasePath}”);
}
}
无法在开箱即用的情况下为sqlite db添加密码保护,更详细的原因有完整的解释 但是,如果您愿意投资,本文中展示了一个很好的解决方案,使用它可以对您的每页数据库进行加密 如果您想按需加密和解密整个db文件,请使用 但正如您所注意到的,实现这种保护的唯一方法是通过对db文件进行加密,您将无法设置密码。我在上写了一篇文章。您可以通过向
UseSqlite
传递一个开放连接,在EF-Core中利用它
使用以下软件包代替Microsoft.EntityFrameworkCore.Sqlite:
- Microsoft.EntityFrameworkCore.Sqlite.Core
- SQLitePCLRaw.bundle\u sqlcipher
这不完全是对你问题的回答,而是一个建议。 您可以使用名为Akavache的库来存储数据 有四个存储位置: -BlobCache.LocalMachine-设备存储 -BlobCache.UserAccount-用户 设置。一些系统将这些数据备份到云中。 -安全-用于保存敏感数据,如凭据。(加密) -BlobCache.InMemory—保存在内存中的数据库。数据 在应用程序的生命周期内存储
希望这有帮助谢谢你的回答,但有两点我不明白。首先,您使用的是变量
\u connection
,下一行使用的是connection
,这是两个不同的变量吗?第二点是,我看不出数据库文件将保存在哪里。@AhmedShamel对于你的第一个问题,我很确定这是一个拼写错误。对于第二个问题,您可以使用的第二个构造函数抱歉,这当然不是一个完整的代码清单,只是一些让您开始。上面以\u
开头的变量应该是类上的字段。默认情况下(Microsoft.EntityFrameworkCore.Sqlite
)使用bundle\u green(普通的Sqlite构建)Microsoft..Sqlite.Core
允许您自带捆绑包。bundle_sqlcipher是一个名为sqlcipher的SQLite的构建,它支持加密。我不这么认为。System.Data.SQLite加密与SQLCipher是一种非常不同的实现。System.Data.SQLite使用的算法仅适用于Windows(不受支持)。
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
// TODO: Dispose with DbContext
_connection = new SqliteConnection(_connectionString);
_connection.Open();
// TODO: Avoid SQL injection (see post)
var command = _connection.CreateCommand();
command.CommandText = "PRAGMA key = '" + _password + "'";
command.ExecuteNonQuery();
options.UseSqlite(_connection);
}