我需要面对一个新的小项目。它将有大约7到9个表,其中最大的一个表每月增长速度最多为1000行。
我想使用SQLite作为我的数据库......但是如果有人想要更改数据库中的数据,我需要保护它。
我的主要问题是:
是否可以像在Access上那样给SQLite数据库设置密码保护?
开发语言将采用C#,但我正在寻找一些免费的解决方案。
我需要面对一个新的小项目。它将有大约7到9个表,其中最大的一个表每月增长速度最多为1000行。
我想使用SQLite作为我的数据库......但是如果有人想要更改数据库中的数据,我需要保护它。
我的主要问题是:
是否可以像在Access上那样给SQLite数据库设置密码保护?
开发语言将采用C#,但我正在寻找一些免费的解决方案。
你可以为SQLite3数据库设置密码。在执行任何操作之前,请按照以下步骤设置密码。
SQLiteConnection conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
conn.SetPassword("password");
conn.Open();
那么下一次您可以像这样访问它
conn = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;Password=password;");
conn.Open();
这将防止任何GUI编辑器查看您的数据。如果您提供密码,某些编辑器可以解密数据库。使用的算法是RSA。
以后如果您想要更改密码,请使用
conn.ChangePassword("new_password");
要重置或删除密码,请使用
conn.ChangePassword(String.Empty);
// Opens an unencrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
// Encrypts the database. The connection remains valid and usable afterwards.
cnn.ChangePassword("mypassword");
ChangePassword()
函数:// Opens an encrypted database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3;Password=mypassword");
cnn.Open();
// Removes the encryption on an encrypted database.
cnn.ChangePassword(null);
ConnectionString
中指定密码,如上例所示,或在打开新的SQLiteConnection
之前调用SetPassword()
函数。在ConnectionString
中指定的密码必须是明文,但在SetPassword()
函数中提供的密码可以是二进制字节数组。// Opens an encrypted database by calling SetPassword()
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.SetPassword(new byte[] { 0xFF, 0xEE, 0xDD, 0x10, 0x20, 0x30 });
cnn.Open();
// The connection is now usable
默认情况下,使用ATTACH关键字将在将另一个数据库文件附加到现有连接时使用与主数据库相同的加密密钥。要更改此行为,可以使用以下KEY修饰符:
如果您正在使用明文密码附加加密的数据库:
// Attach to a database using a different key than the main database
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY 'mypassword'", cnn);
cmd.ExecuteNonQuery();
使用二进制密码附加加密数据库:
// Attach to a database encrypted with a binary key
SQLiteConnection cnn = new SQLiteConnection("Data Source=c:\\test.db3");
cnn.Open();
cmd = new SQLiteCommand("ATTACH DATABASE 'c:\\pwd.db3' AS [Protected] KEY X'FFEEDD102030'", cnn);
cmd.ExecuteNonQuery();
使用SQLCipher,它是SQLite的开源扩展,可以为数据库文件提供透明的256位AES加密。http://sqlcipher.net
private ISessionFactory createSessionFactory()
{
return Fluently.Configure()
.Database(SQLiteConfiguration.Standard.UsingFileWithPassword(filename, password))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<DBManager>())
.ExposeConfiguration(this.buildSchema)
.BuildSessionFactory();
}
private void buildSchema(Configuration config)
{
if (filename_not_exists == true)
{
new SchemaExport(config).Create(false, true);
}
}
方法UsingFileWithPassword (文件名,密码)加密数据库文件并设置密码。
仅在创建新的数据库文件时运行。旧文件未加密,如果使用此方法打开,则会打开失败。
其中一个选择是VistaDB。它可以对数据库(甚至是表格)进行密码保护(可选加密)。