ios中的SQL数据库文件加密 (使用sqlcipher)

今天本想写一片 GAE+goAgent+SwitchySharp 的指南的!但是突然翻出了前段时间写的关于ios中的SQL数据库文件加密的代码,于是乎决定今天就先讲讲这个!~ 那么goAgent将放在周末,  后续的文章中除了文件加密,还有传输数据加密,感兴趣的童鞋 敬请留意。

言归正传,sql的文件加密,我们首先要用到一个库,它就是大名鼎鼎的Sqlcipher,  奉上连接:http://sqlcipher.net,在ios里 我们需要看的文档是这一篇http://sqlcipher.net/ios-tutorial/,文档是全英文的,在此,不详细阐述,只按步骤教大家怎么做,至于为什么做的问题,就需要自己去寻找答案了!

1.下载需要的库 这里我们总共需要3个目录的文件,分别是sqlcipher,openssl-xcode,openssl-1.0.0e。

首先下载第一个

[plain]  view plain copy
  1. % cd ~/Documents/code//命令行cd到你要下载的目录  
  2. % curl -o openssl-1.0.0e.tar.gz http://www.openssl.org/source/openssl-1.0.0e.tar.gz//下载  
  3. % tar xzf openssl-1.0.0e.tar.gz //解压缩    


附:

SQLCipher uses the widely trusted and peer-reviewed OpenSSL library for all cryptographic functions including the AES-256 algorithm, pseudo random number generation, and PBKDF2 key derivation. OpenSSL isn't framework that is usable directly on the iPhone so we will setup our project to build and link against it as a static library.
Download the 1.0.x stable version from http://www.openssl.org/source/ and extract it to a folder on your system. Since the same OpenSSL source tree may be shared across multiple SQLCipher projects, it's a good idea to place this in some shared location outside of your project folder. Justs make a note of the source directory path for later.

(看不懂英文的童鞋也不用着急,跟着继续做就好了,也很好理解)

OpenSSL是套开源SSL套件,其函数库是以C語言所写,实现基本的傳輸層資料加密功能。

第二个

[plain]  view plain copy
  1. % cd ~/Documents/code/SQLCipherApp  
  2. % git clone https://github.com/sqlcipher/sqlcipher.git  
从远端服务器将其 clone 下来,这里推荐放到和上一个文件同一个目录 方便管理

这个就是 sqlcipher 的project code了

第三个

[plain]  view plain copy
  1. % cd ~/Documents/code/SQLCipherApp  
  2. % git clone https://github.com/sqlcipher/openssl-xcode.git  

这个是我们需要动态编译进工程的文件

至此我们需要的文件 就准备好了


接下来 打开你的工程进行配置,

(这里我是自己单独写了一个工具用来加密并生成!后面会附上我的源码)

1.将你下载的3个目录拷贝进你的工程目录

2.点击你xcode的设置页,选择locations ->source trees



点击+号  settingname and display name 均设为  “OPENSSL_SRC”       path设置为你工程目录下openssl-1.0.0e的所在路径



3.添加子项目的引用

将刚才下载的文件里的openssl.xcodeproj 和sqlcipher.xcodeproj (分别在openssl-xcode文件和sqlcipher文件下)添加到你的主工程下,建立引用,直接看图吧!





4,接下来 配置编译依赖的库,这是必须的!~

点击你的工程TARGETS 进入build phases ->target dependencies,添加图中的两个项目



接下来点击同一个页面下的link binary with libraries添加这两个库



至此 还有最后一步,设置编译设置

点击你的工程project->build settings ->搜索architectures进行设置

我这里由于是mac程序看起来会是这样



iOS的话 会是这样



(关于这里的设置,如果又不明白的地方 请google)

接下来 还是在同页面 搜索“other c flags”

进行如下配置



至此整个过程就打工告成了

接下来讲述使用

首先在需要的文件内 import<sqlite3.h>

下面 示范一个 创建or打开数据库的函数

[html]  view plain copy
  1. -(BOOL) openDatabase  
  2. {  
  3.     if (sqlite3_open([[self dataFilePath:DB_NAME] UTF8String], &_database) == SQLITE_OK) {  
  4.         const char* key = [@",66c9a^N" UTF8String];    //数据库文件加密  
  5.         sqlite3_key(_database, key, (int)strlen(key));      //数据库文件加密  
  6.         NSLog(@"\n===数据库打开or创建成功===\n");  
  7.         return YES;  
  8.     }else{  
  9.         NSLog(@"\n===数据库打开失败===\n");  
  10.     }  
  11.     return NO;  
  12. }  

DB_NAME 是定义的 数据库文件名的宏",66c9a^N" 是你要设置的数据库密钥 sqlite3_key(_database, key, (int)strlen(key));这个方法里就包含了 加解密的过程!~是不是非常简单呢嘿嘿接下来 附上自己的工程 源代码有需要的童鞋,就自己看看吧!里面有详细的注释, 也简单的实现了几个方便数据库操作的函数





[html]  view plain copy
  1. //////////////////////////////////////////////////////////  
  2. #import <Foundation/Foundation.h>  
  3. #import <sqlite3.h>  
  4. #define DB_NAME @"xxxxxxx.db"                            //数据库文件名  
  5. @interface SqliteHelp :NSObject  
  6. @propertysqlite3 *database;                       //数据库句柄  
  7. @propertysqlite3_stmt *statement;                 //sql语句  
  8. @property char *errmsg;  
  9. -(BOOL) openDatabase;                              //打开数据库  这个函数一般不直接调用,而是直接调用对数据库操作的函数  
  10. -(void) closeDataBase;                             //关闭数据库  这个函数一般不直接调用,而是直接调用对数据库操作的函数  
  11. -(NSString *) dataFilePath:(NSString *)fileName;   //返回数据库存储路径 这个函数一般不直接调用,而是直接调用对数据库操作的函数  
  12. /**  
  13.  * 说明: 给定一个SQL语句 插入或者编辑一个数据  
  14.  * 语句格式 :  
  15.  * 插入:[insert (文件名)values(data1, data2, data3, ...);]  
  16.  * 编辑:[update(文件名) set (字段名)=(修改后的数据) where(字段名)=(修改前的数据);]  
  17.  */  
  18. -(BOOL) insertOrUpdateData:(NSString *)sql;  
  19.             
  20. -(NSMutableArray *) getUsers;                      //以数组的形势,获取所有用户  
  21. -(int) getCountOfDatabase;                         //获取当前数据库的数量  
  22. @end  
  23. ////////////////////////////////////////////////////  
  24. #import "SqliteHelp.h"  
  25. @implementation SqliteHelp  
  26. @synthesize database =_database;  
  27. @synthesize statement =_statement;  
  28. @synthesize errmsg =_errmsg;  
  29. -(BOOL) openDatabase  
  30. {  
  31.    if (sqlite3_open([[selfdataFilePath:DB_NAME]UTF8String], &_database) ==SQLITE_OK) {  
  32.        constchar* key = [@",66c9a^N"UTF8String];   //数据库文件加密  
  33.        sqlite3_key(_database, key, (int)strlen(key));     //数据库文件加密  
  34.         NSLog(@"\n===数据库打开or创建成功===\n");  
  35.        returnYES;  
  36.     }else{  
  37.         NSLog(@"\n===数据库打开失败===\n");  
  38.     }  
  39.     return NO;  
  40.       
  41. }  
  42. -(void) closeDataBase  
  43. {  
  44.     sqlite3_close(_database);  
  45. }  
  46. -(NSString *) dataFilePath:(NSString *)fileName  
  47. {  
  48.     NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,  
  49.                                                         NSUserDomainMask,  
  50.                                                         YES);  
  51.    NSString *documentsDirectory = [pathsobjectAtIndex:0];  
  52.    return [documentsDirectorystringByAppendingPathComponent:fileName];  
  53. }  
  54. -(BOOL) insertOrUpdateData:(NSString *)sql  
  55. {  
  56.    if ([selfopenDatabase]) {  
  57.        if (sqlite3_exec(_database, [sqlUTF8String],nil, &_statement, &_errmsg) !=SQLITE_OK) {  
  58.             NSLog(@"\n===插入数据失败===\n");  
  59.             NSLog(@"\n==sql Error:%s",_errmsg);  
  60.            returnNO;  
  61.         }else{  
  62.             NSLog(@"\n===插入数据成功===\n");  
  63.            returnYES;  
  64.         }  
  65.          
  66.     }  
  67.     sqlite3_close(_database);  
  68.     return NO;  
  69. }  
  70. -(NSMutableArray *) seeDatabase  
  71. {  
  72.     NSMutableArray *users = [[NSMutableArrayalloc]init];  
  73.     NSString *sql = [NSStringstringWithFormat:@"SELECT * FROM t_relive"];  
  74.    if ([selfopenDatabase]) {  
  75.        if (sqlite3_prepare_v2(_database, [sqlUTF8String], -1, &_statement,nil) ==SQLITE_OK) {  
  76.            while (sqlite3_step(_statement) ==SQLITE_ROW ) {  
  77. //                User *user = [[Question alloc] init];  
  78.                int name =sqlite3_column_int(_statement,0);  
  79. //                [user setName:[NSString stringWithUTF8String:name]];  
  80.                int index =sqlite3_column_int(_statement,1);  
  81. //                [user setId:[[NSString stringWithUTF8String:index] intValue]];  
  82. //                [users addObject: user];  
  83.                NSLog(@"%i=%i",name,index);  
  84.             }  
  85.             sqlite3_finalize(_statement);  
  86.         }  
  87.     }  
  88.     sqlite3_close(_database);  
  89.    return users;  
  90. }  
  91. -(int) getCountOfDatabase  
  92. {  
  93.    int count =0;  
  94.     NSString *sql = [NSStringstringWithFormat:@"SELECT * FROM User"];  
  95.    if ([selfopenDatabase]) {  
  96.        if (sqlite3_prepare_v2(_database, [sqlUTF8String], -1, &_statement,nil) ==SQLITE_OK) {  
  97.            while (sqlite3_step(_statement) ==SQLITE_ROW) {  
  98.                 count ++;  
  99.             }  
  100.             sqlite3_finalize(_statement);  
  101.         }  
  102.     }  
  103.    return count;  
  104. }  
  105. @end  
  106. /////////////////////////////////////////////////////////////////  
  107. 这里实现 输入sql表 生成数据库,可以在控制台查错  
  108. #import "AppDelegate.h"  
  109. #import "SqliteHelp.h"  
  110. @implementation AppDelegate  
  111. - (void)applicationDidFinishLaunching:(NSNotification *)aNotification  
  112. {  
  113.     // Insert code here to initialize your application  
  114.     [selfbuildDatabase];  
  115.     [selfinsertDatabase];  
  116. }  
  117. - (void) buildDatabase  
  118. {  
  119.    NSError *error;  
  120.     NSString *textFile = [NSStringstringWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"schema.sqlite.tables.sql"ofType:nil]encoding:NSUTF8StringEncodingerror:&error];  
  121.    if (textFile ==nil) {  
  122.         NSLog(@"Error reading text file. %@", [errorlocalizedFailureReason]);  
  123.     }  
  124.     NSArray *row = [textFilecomponentsSeparatedByString:@";"];  
  125.    NSInteger count = [rowcount];  
  126.     SqliteHelp *t = [SqliteHelpnew];  
  127.    for (int i=0; i<count; i++) {  
  128.        NSString *tempString = [NSStringstringWithFormat:@"%@;",row[i]];  
  129.        NSLog(@"%@",tempString);  
  130.         [tinsertOrUpdateData:tempString];  
  131.     }  
  132.       
  133.       
  134.       
  135. }  
  136. -(void) insertDatabase  
  137. {  
  138.    NSError *error;  
  139.     NSString *textFile = [NSStringstringWithContentsOfFile:[[NSBundlemainBundle]pathForResource:@"schema.sqlite.data.sql"ofType:nil]encoding:NSUTF8StringEncodingerror:&error];  
  140.    if (textFile ==nil) {  
  141.         NSLog(@"Error reading text file. %@", [errorlocalizedFailureReason]);  
  142.     }  
  143.     NSArray *row = [textFilecomponentsSeparatedByString:@";"];  
  144.    NSInteger count = [rowcount];  
  145.     SqliteHelp *t = [SqliteHelpnew];  
  146.    for (int i=0; i<count; i++) {  
  147.        NSString *tempString = [NSStringstringWithFormat:@"%@;",row[i]];  
  148.        NSLog(@"%@",tempString);  
  149.         [tinsertOrUpdateData:tempString];  
  150.     }  
  151.       
  152. }  
[html]  view plain copy
  1. @end  
[plain]  view plain copy
  1. <pre name="code" class="plain" style="font-size: 11px; "><pre name="code" class="plain" style="font-size: 11px; "><pre></pre>  
  2. <pre></pre>  
  3. <pre></pre>  
  4. <pre></pre>  
  5. <pre></pre>  
  6. <pre></pre>  
  7. <pre></pre>  
  8. <pre></pre>  
  9. <pre></pre>  
  10. <pre></pre>  
  11. <pre></pre>  
  12. <pre></pre>  
  13. <pre></pre>  
  14. <pre></pre>  
  15. <pre></pre>  
  16. <pre></pre>  
  17. <pre></pre>  
  18. <pre></pre>  
  19. <pre></pre>  
  20. <pre></pre>  
  21. <pre></pre>  
  22. <pre></pre>  
  23. <pre></pre>  
  24. <pre></pre>  
  25. <pre></pre>  
  26. <pre></pre>  
  27.   
  28. </pre></pre>  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
提供的源码资源涵盖了Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!
提供的源码资源涵盖了小程序应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 适合毕业设计、课程设计作业。这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。 所有源码均经过严格测试,可以直接运行,可以放心下载使用。有任何使用问题欢迎随时与博主沟通,第一时间进行解答!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值