在Xamarin表单中为Sqlite文件添加密码

问题描述 投票:9回答:3

我有一个Xamarin表单应用程序,它创建一个Sqlite数据库。

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}");    
        }
    }
c# sqlite xamarin.forms entity-framework-core
3个回答
4
投票

我写了一篇关于Encryption in Microsoft.Data.Sqlite的帖子。您可以通过传递到UseSqlite的开放连接在EF Core中利用它。

而不是Microsoft.EntityFrameworkCore.Sqlite,使用这些包:

  • Microsoft.EntityFrameworkCore.Sqlite.Core
  • SQLitePCLRaw.bundle_sqlcipher

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

0
投票

没有办法为开箱即用的sqlite db添加密码保护,有更详细的原因有here的完整解释。

但是,如果你愿意投入资金,这个thread上有一个很好的解决方案,使用SQL Chiper来加密每页数据库。

如果要按需加密和解密整个db文件,请使用PCLCrypto

但是正如您所注意到的,实现这种保护的唯一方法是通过加密db文件,您将无法设置密码。


0
投票

不完全是你的问题的答案,而是一个建议。您可以使用名为Akavache的库来存储数据。

有四个存储位置: - BlobCache.LocalMachine - 设备存储 - BlobCache.UserAccount - 用户设置。有些系统会将此数据备份到云端。 - BlobCache.Secure - 用于保存敏感数据 - 如凭据。(加密) - BlobCache.InMemory - 保存在内存中的数据库。数据存储在应用程序的生命周期中。

希望有所帮助

© www.soinside.com 2019 - 2024. All rights reserved.