C# 利用SQLite对.DB和.logdb加密和解密和SQLite创建数据库

1.最近研究了下利用SQLite为db文件简单的加密和解密

 1  private static SQLiteConnection GetConnection()
 2         {
 3             SQLiteConnection conn;
 4             string password = dataProvider.ConfigSearch(ConfigCode.SYS_File_ENCRYPTION_PASSWORD, true)[0].Value;
 5             string dbFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), ConfigCode.CLIENT_DATA_PATH);
 6             string dbPath = Path.GetDirectoryName(dbFile);
 7             if (!Directory.Exists(dbPath))
 8             {
 9                 Directory.CreateDirectory(dbPath);
10             }
11             if (!File.Exists(dbFile))
12             {
13                 //数据库不存在,则创建
14                 SQLiteConnection.CreateFile(dbFile);
15                 CommonUtils.SetAccessControlList(dbFile);
16                 conn = new SQLiteConnection(string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dbFile));
17                 conn.Open();
18                 conn.ChangePassword(password);
19                 if (string.IsNullOrEmpty(install_db_sql))
20                 {
21                     install_db_sql = Path.Combine(Path.GetDirectoryName(typeof(SQLiteProvider).Assembly.Location), "setup.sql");
22                 }
23 
24                 foreach (string line in File.ReadAllText(install_db_sql).Split(new char[] { ';' }))
25                 {
26                     if (String.IsNullOrEmpty(line))
27                     {
28                         continue;
29                     }
30                     SQLiteCommand cmd = conn.CreateCommand();
31                     cmd.CommandText = line;
32                     cmd.CommandType = CommandType.Text;
33                     cmd.ExecuteNonQuery();
34                     cmd.Dispose();
35                 }
36             }
37             else
38             {
39                 try
40                 {
41                     conn = new SQLiteConnection(string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dbFile));
42                     conn.SetPassword(password);
43                     conn.Open();
44                     conn.ChangePassword(password);
45                 }
46                 catch (Exception)
47                 {
48                     conn = new SQLiteConnection(string.Format("Data Source={0};Pooling=true;FailIfMissing=false", dbFile));
49                     conn.Open();
50                 }
51                 
52             }
53             return conn;
54         }
View Code

 这里为了兼顾以前没有加密的数据库文件,特意做了处理,如果数据库不存在,直接创建,加密就不存在这个问题,主要是针对已经存在的数据库有个try...catch的异常处理,个人已验证,可以直接拿去用。

 

转载于:https://www.cnblogs.com/myfy/p/6047985.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值