天天看點

c# sqlite 資料庫加密

用了 ADO.NET 2.0 SQLite Data Provider 這樣可以直接利用它來建立一個 加密的sqlite資料庫。

有關c#代碼如下:

1、建立空的sqlite資料庫。 // 資料庫名的字尾你可以直接指定,甚至沒有字尾都可以

// 方法一:建立一個空sqlite資料庫,用IO的方式

FileStream fs = File.Create( “ c://test.db “ );

// 方法二:用SQLiteConnection

SQLiteConnection.CreateFile( “ c://test.db “ );

建立的資料庫是個0位元組的檔案。

2、建立加密的空sqlite資料庫

// 建立一個密碼為password的空的sqlite資料庫

SQLiteConnection.CreateFile( “ c://test2.db “ );                

SQLiteConnection cnn = new SQLiteConnection( “ Data Source=c://test2.db “ );

SQLiteConnection cnn = new SQLiteConnection( “ Data Source=D://test2.db “ );

cnn.Open();

cnn.ChangePassword( “ password “ );

3、給未加密的資料庫加密

SQLiteConnection cnn = new SQLiteConnection( “ Data Source=c://test.db “ );

cnn.Open();

cnn.ChangePassword( “ password “ );

4、打開加密sqlite資料庫

//方法一

SQLiteConnection cnn = new SQLiteConnection(“Data Source=c://test2.db“);

cnn.SetPassword(“password“);

cnn.Open();

//方法二

SQLiteConnectionStringBuilder builder = new SQLiteConnectionStringBuilder();

builder.DataSource = @”c:/test.db“;

builder.Password = @”password“;

SQLiteConnection cnn = new SQLiteConnection(builder.ConnectionString);

cnn .Open();

注:

A、因為加密的函數是利用windows api,故加密後的資料庫隻能适用在windows平台,加密的方式是整體檔案加密。

B、加密的算法是RC4,如果你想采用别的加密算法來加密,請參考ADO.NET 2.0 SQLite Data Provider 的源碼來修改。

c、相關sqlite資料庫操作類似ADO.NET 2.0。詳見ADO.NET 2.0 SQLite Data Provider的幫助文檔。

c、ADO.NET 2.0 SQLite Data Provider 版本為:1.0.53.0 ,SQLite版本 : 3.6.0。

d、開發環境為vs2008。