请给出完整的c#代码
时间: 2024-09-13 19:14:30 浏览: 35
C#仓库管理系统+完整源代码
5星 · 资源好评率100%
当然,我可以给你展示一个简单的C#代码片段,用于在SQLite数据库中设置加密。这里我们假设你已经设置了`System.Data.SQLite` NuGet包,并且已经有了一个数据库连接实例`conn`。我们将使用`System.Security.Cryptography`中的`Aes`加密进行演示:
```csharp
using System;
using System.IO;
using System.Security.Cryptography;
using SQLite;
class Program
{
static void Main(string[] args)
{
string password = "your_database_password"; // 设置你的加密密码
byte[] salt = GenerateSalt();
// 使用密码生成盐并加密数据
string sensitiveDataToStore = "Sensitive data to encrypt";
byte[] encryptedData = EncryptData(sensitiveDataToStore, password, salt);
// 执行SQL语句启用数据库加密
using (var conn = new SQLiteConnection("Data Source=mydatabase.db;Pragma=encryption_key='" + Convert.ToBase64String(salt) + "'"))
{
conn.Open();
conn.ExecuteNonQuery($"PRAGMA key = '{password}';");
// 插入加密后的数据
var command = conn.CreateCommand();
command.CommandText = "INSERT INTO MyTable (EncryptedData) VALUES (@data)";
command.Parameters.AddWithValue("@data", Convert.ToBase64String(encryptedData));
command.ExecuteNonQuery();
}
Console.WriteLine("Data has been encrypted and stored.");
}
// 生成随机盐值
private static byte[] GenerateSalt()
{
using (var rng = RandomNumberGenerator.Create())
{
return rng.GetBytes(16); // 使用16字节作为默认盐值长度
}
}
// 加密数据
private static byte[] EncryptData(string data, string password, byte[] salt)
{
using (Aes aes = Aes.Create())
{
aes.KeySize = 256;
aes.BlockSize = 128;
var key = DeriveKeyAndIV(password, salt, aes.KeySize / 8);
aes.Key = key.Key;
aes.IV = key.IV;
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
{
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
swEncrypt.Write(data);
}
return msEncrypt.ToArray();
}
}
}
}
}
// 使用PBKDF2DeriveBytes函数生成密钥和初始化向量
private static Rfc2898DeriveBytes DeriveKeyAndIV(string password, byte[] salt, int iterations)
{
Rfc2898DeriveBytes deriveBytes = new Rfc2898DeriveBytes(password, salt, iterations);
return deriveBytes;
}
}
```
这段代码展示了如何开启数据库加密、生成盐值、加密数据以及将其存储到数据库中。注意实际应用中,你需要处理异常,以及在登录验证时解密数据。
阅读全文