You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.NET MAUI中加密SQLite数据库?求替代加密NuGet包

在.NET MAUI中为SQLite数据库添加加密支持

支持加密的NuGet包选项

  • SQLite-net-sqlcipher:与你当前使用的SQLite-net-pcl完全兼容,基于SQLCipher实现AES-256加密,是最直接的替代/扩展方案。
  • SQLitePCLRaw.bundle_sqlcipher:提供底层SQLCipher原生库支持,适合需要更精细控制加密逻辑的场景,可与SQLite-net-pcl配合使用。

具体实现步骤

1. 安装加密NuGet包

优先推荐安装SQLite-net-sqlcipher,它会自动处理跨平台的原生依赖,无需额外配置。

2. 修改数据库连接代码

在创建SQLiteAsyncConnection时,通过SQLiteConnectionString传入加密密钥,替换你原有的连接逻辑:

if (_dbConnection == null)
{
    string dbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Funds.db3");
    // 注意:密钥请勿硬编码,建议使用.NET MAUI的SecureStorage存储
    string encryptionKey = await SecureStorage.GetAsync("DbEncryptionKey");
    
    // 配置加密连接:第二个参数为true表示自动加密新数据库
    var connectionConfig = new SQLiteConnectionString(dbPath, true, encryptionKey);
    _dbConnection = new SQLiteAsyncConnection(connectionConfig);
    
    await _dbConnection.CreateTableAsync<FundsModel>();
}

3. 密钥安全存储建议

不要将加密密钥硬编码到代码中,使用.NET MAUI的SecureStorage安全存储密钥:

// 首次设置密钥(仅执行一次)
await SecureStorage.SetAsync("DbEncryptionKey", "YourStrongUniqueKeyHere!");

// 后续获取密钥
string encryptionKey = await SecureStorage.GetAsync("DbEncryptionKey");

注意事项

  • 若要加密已存在的未加密数据库,需先导出原有数据,再创建加密数据库并导入数据,直接使用密钥连接未加密数据库会导致错误。
  • 跨平台兼容性:SQLCipher原生库已适配Android、iOS、Windows等.NET MAUI支持的平台,安装NuGet包后会自动引入对应平台的依赖。

内容的提问来源于stack exchange,提问作者Jeandrė De Villiers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 18:54:24