C# Sqlite SQLCipher 加密

安装

    ● Visual Studio PowerShell

Remove-Package Microsoft.Data.Sqlite
Install-Package Microsoft.Data.Sqlite.Core
Install-Package SQLitePCLRaw.bundle_e_sqlcipher

    ● 在 Nuget Package Manager 安装

选择 Microsoft.Data.Sqlite.CoreSQLitePCLRaw.bundle_e_sqlcipher

导入包

using Microsoft.Data.Sqlite;
using System;

连接已加密的数据库

public static void Main() {
    var connectionString = new SqliteConnectionStringBuilder() {
        Mode = SqliteOpenMode.ReadWrite,
        Password = "123", // 数据库密码
        DataSource = "resource/database.db", // 数据库文件路径
    }.ToString();
    SqliteConnection connection = new SqliteConnection(connectionString);
    connection.Open();
    Work(connection);
    connection.Close();
}

查询示例

public static void Work(SqliteConnection connection) {
    var command = connection.CreateCommand();
    command.CommandText = @"select count(*) from t_user";

    using (var reader = command.ExecuteReader()) {
        while (reader.Read()) {
            int n = reader.GetInt32(0);
            Console.WriteLine($"t_user 一共有 {n} 行");
        }
    }
}

修改已加密的数据库密码

public static void Work(SqliteConnection connection) {
    var command = connection.CreateCommand();
    string newPassword = "12345";
    command.CommandText = $"PRAGMA rekey = '${newPassword}'";
    command.ExecuteNonQuery();
}

参考链接

https://docs.microsoft.com/en-us/dotnet/standard/data/sqlite/encryption?tabs=visual-studio
https://www.zetetic.net/sqlcipher/

SQLCipher 是一个基于SQLite加密扩展,可以用于在C#应用程序中为SQLite数据库提供加密功能。在C#中使用SQLCipher加密SQLite数据库需要以下步骤: 1. 下载SQLCipher库文件并将其添加到C#项目中。 2.C#代码中使用SQLiteConnection类创建一个SQLite数据库连接,并使用SQLCipher加密密钥对其进行加密。 ``` using System.Data.SQLite; using System.Security.Cryptography; string databasePath = @"C:\path\to\database.db"; string password = "myPassword"; byte[] salt = new byte[16] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 }; byte[] key = new Rfc2898DeriveBytes(password, salt).GetBytes(16); SQLiteConnection connection = new SQLiteConnection("Data Source=" + databasePath); connection.SetPassword(key); connection.Open(); ``` 在上面的示例中,我们使用Rfc2898DeriveBytes类从密码和盐中生成16字节的加密密钥,并使用SetPassword方法将其应用于SQLite连接。 3. 执行SQL命令来创建表和插入数据等操作。 ``` SQLiteCommand command = new SQLiteCommand("CREATE TABLE myTable (id INTEGER PRIMARY KEY, name TEXT)", connection); command.ExecuteNonQuery(); command = new SQLiteCommand("INSERT INTO myTable (name) VALUES ('John Doe')", connection); command.ExecuteNonQuery(); ``` 在上面的示例中,我们使用SQLiteCommand类来执行SQL命令。 4. 在完成对数据库的操作后,关闭SQLite连接。 ``` connection.Close(); ``` 以上就是在C#应用程序中使用SQLCipher加密SQLite数据库的步骤。需要注意的是,为了保证安全性,应该使用强密码来生成加密密钥,并且不要将密码硬编码到应用程序中。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值