请稍侯

使用 sqlcipher 加密解密 sqlite3 数据库

09 August 2020

使用 sqlcipher 加密解密 sqlite3 数据库

下载sqlcipher

https://github.com/sqlcipher/sqlcipher

编译sqlcipher

$ ./configure --enable-tempstore=yes CFLAGS="-DSQLITE_HAS_CODEC" LDFLAGS="-lcrypto -L/usr/local/opt/openssl/lib" CPPFLAGS="-I/usr/local/opt/openssl/include"
$ make

安装sqlcipher

  • 创建一个sqlcipher新的目录;
  • 再把之前编译的 sqlcipher 二进制可执行文件 与 .libs 库文件目录添加到新创建的sqlcipher目录;
  • 再把sqlcipher目录下的sqlcipher文件软链接到path能找得到的目录下,如:/usr/local/bin目录下,如:ln -s /Users/luowei/developer/sqlcipher/sqlcipher /usr/local/bin/sqlcipher

加密已有明文数据库

~ $ sqlcipher WubiWords.db
sqlite> ATTACH DATABASE 'encrypted_wbwords.db' AS wubiwords KEY 'xxxxxxxx';
sqlite> SELECT sqlcipher_export('wubiwords');
sqlite> DETACH DATABASE wubiwords;
sqlite> .exit

解密加密了的数据库:

$ ./sqlcipher encrypted_wbwords.db
sqlite> PRAGMA key = 'xxxxxxxx';
sqlite> ATTACH DATABASE 'decrypted_wbwords.db' AS wubiwords KEY '';  --空的密码不会加密数据库
sqlite> SELECT sqlcipher_export('wubiwords');
sqlite> DETACH DATABASE wubiwords;
sqlite> .exit

集成sqlcipher

集成方式可以在Xcode上直接集成源代码,或先编译成静态库文件后,再集成; 要在Xcode上集成,在GitHub上下载的sqlcipher中有个sqlcipher.xcodeproj文件,只要在你的xcode项目根目录右键选择“Add Files To xxx”,然后把sqlcipher.xcodeproj这个文件添加到你的项目,在目标依赖中添加Security.framework 和 libsqlcipher.a 这两个链接库,如果没有找到libsqlcipher.a可以先构建sqlcipher.xcodeproj这个项目。

合并静态库文件

lipo -create Debug-iphoneos/libsqlcipher.a Debug-iphonesimulator/libsqlcipher.a -output libsqlcipher-iOS-Debug.a

lipo -create Release-iphoneos/libsqlcipher.a Release-iphonesimulator/libsqlcipher.a -output libsqlcipher-iOS-Release.a

使用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);
}

##参考: IOS集成SQLCipher加密SQLite数据库 SQLite extension SQLCipher