.html
转自王中周的个人博客
关于SQLite
SQLite是一个轻量的、跨平台的、开源的数据库引擎,它的在读写效率、消耗总量、延迟时间和整体简单性上具有的优越性,使其成为移动平台数据库的最佳解决方案(如iOS、Android)。 然而免费版的SQLite有一个致命缺点:不支持加密。这就导致存储在SQLite中的数据可以被任何人用任何文本编辑器查看到。比如国内某团购iOS客户端的DB缓存数据就一览无余:SQLite Encryption Extension (SEE)版本是收费的。 SQLiteEncrypt 使用AES加密,其原理是实现了开源免费版SQLite没有实现的加密相关接口。 SQLiteEncrypt是收费的。 SQLiteCrypt 使用256-bit AES加密,其原理和 SQLiteEncrypt一样,都是实现了SQLite的加密相关接口。 SQLiteCrypt也是收费的。 SQLCipher 首先需要说明的是,SQLCipher是完全开源的,代码托管在 Github上。 SQLCipher使用256-bit AES加密,由于其基于免费版的SQLite,主要的加密接口和SQLite是相同的,但也增加了一些自己的接口,详情见 这里。 SQLCipher分为收费版本和免费版本,官网介绍的区别为:
- RC4
- AES-128 in OFB mode
- AES-128 in CCM mode
- AES-256 in OFB mode
asier to setup, saving many steps in project configuration pre-built with a modern version of OpenSSL, avoiding another external dependency much faster for each build cycle because the library doesn't need to be built from scratch on each compile (build time can be up to 95% faster with the static libraries) |
需要注意的是,在使用sqlite3_open打开或创建一个数据库,在对数据库做任何其它操作之前,都必须先使用sqlite3_key输入密码,否则会导致数据库操作失败,报出sqlite错误码SQLITE_NOTADB。 在sqlite3_open打开数据库成功,而且用sqlite3_key输入密码以后,就可以正常的对数据库进行增、删、改、查等操作了。 使用SQLCipher加密已存在的数据库 SQLCipher提供了sqlcipher_export()函数,该函数可以方便的对一个普通数据库导入到SQLCipher加密加密的数据库中,操作方式如下:
- NSString *databasePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]
- stringByAppendingPathComponent: @"cipher.db"];
- sqlite3 *db;
- if (sqlite3_open([databasePath UTF8String], &db) == SQLITE_OK) {
- const char* key = [@"BIGSecret" UTF8String];
- sqlite3_key(db, key, strlen(key));
- int result = sqlite3_exec(db, (const char*) "SELECT count(*) FROM sqlite_master;", NULL, NULL, NULL);
- if (result == SQLITE_OK) {
- NSLog(@"password is correct, or, database has been initialized");
- } else {
- NSLog(@"incorrect password! errCode:%d",result);
- }
- sqlite3_close(db);
- }
解除使用SQLCipher加密的数据库密码 sqlcipher_export()函数同样可以将SQLCipher加密后的数据库内容导入到未加密的数据库中,从而实现解密,操作方式如下:
- $ ./sqlcipher plaintext.db
- sqlite> ATTACH DATABASE 'encrypted.db' AS encrypted KEY 'testkey';
- sqlite> SELECT sqlcipher_export('encrypted');
- sqlite> DETACH DATABASE encrypted;
总体来说,SQLCipher是一个使用方便,灵活性高的数据库加密工具。 另外,我写了个 SQLCipherDemo工程放到了 CSDN上,有需要的同学请自行下载。 参考文档 The SQLite Encryption Extension (SEE) SQLiteEncrypt SQLiteCrypt SQLite with encryption/password protection SQLCipher
- $ ./sqlcipher encrypted.db
- sqlite> PRAGMA key = 'testkey';
- sqlite> ATTACH DATABASE 'plaintext.db' AS plaintext KEY ''; -- empty key will disable encryption
- sqlite> SELECT sqlcipher_export('plaintext');
- sqlite> DETACH DATABASE plaintext;
本文发布于:2024-02-04 12:22:40,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170707132955530.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |