簡體   English   中英

不知道如何使用SQLCipher加密數據庫

[英]Don't know how to encrypt database using SQLCipher

我已將SQLCipher包含在我的項目中,與此鏈接中的說明完全相同: http ://sqlcipher.net/ios-tutorial/

但我不知道如何加密數據庫我已從上面的鏈接讀取描述但沒有得到。
實際上我正在做的是如果應用程序第一次打開,那么它會將數據庫(即沒有加密)復制到文檔目錄。 從bundle復制到文檔目錄時,我的數據庫還有一個空白。
我打開數據庫后嘗試使用sqlite3_key函數但沒有加密。 但是我沒有找到類似於從bundle復制到文檔目錄時加密數據庫的東西。 我打算使用FMDB,所以最好根據這個回復。
如果有任何教程,請指導我如何做或指向方向。 還建議應該采用什么標准方法來做到這一點。

對於那些尋找如何實現這一目標的簡單教程的人,我能夠創建一個: http//www.guilmo.com/fmdb-with-sqlcipher-tutorial/

但最重要的部分是,打開現有數據庫並附加新的加密數據庫。 然后在FMDB連接中設置密鑰。

SQLCipher - 加密數據庫

// Import sqlite3.h in your AppDelegate
#import <sqlite3.h>

// Set the new encrypted database path to be in the Documents Folder
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSString *ecDB = [documentDir stringByAppendingPathComponent:@"encrypted.sqlite"];

// SQL Query. NOTE THAT DATABASE IS THE FULL PATH NOT ONLY THE NAME
const char* sqlQ = [[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS encrypted KEY 'secretKey';",ecDB] UTF8String];

sqlite3 *unencrypted_DB;    
if (sqlite3_open([self.databasePath UTF8String], &unencrypted_DB) == SQLITE_OK) {

    // Attach empty encrypted database to unencrypted database
    sqlite3_exec(unencrypted_DB, sqlQ, NULL, NULL, NULL);

    // export database
    sqlite3_exec(unencrypted_DB, "SELECT sqlcipher_export('encrypted');", NULL, NULL, NULL);

    // Detach encrypted database
    sqlite3_exec(unencrypted_DB, "DETACH DATABASE encrypted;", NULL, NULL, NULL);

    sqlite3_close(unencrypted_DB);
}
else {
    sqlite3_close(unencrypted_DB);
    NSAssert1(NO, @"Failed to open database with message '%s'.", sqlite3_errmsg(unencrypted_DB));
}

self.databasePath = [documentDir stringByAppendingPathComponent:@"encrypted.sqlite"];

請注意,我們在SQL Query,DATABASE和KEY中設置了2個參數。 DATABASE應該是您要創建的加密數據庫的完整路徑 ,在本例中為字符串ecDB,KEY參數是用於加密數據庫的密鑰,因此選擇一個強大的數據庫

現在在FMDB函數上,每次打開數據庫后調用[db setKey:@“strongKey”]

// FMDatabase Example
FMDatabase *db = [FMDatabase databaseWithPath:[self getDatabasePath]];
[db open];
[db setKey:@"secretKey"];


// FMDatabaseQueue Exmple
FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self getDatabasePath]];

[queue inDatabase:^(FMDatabase *db) {
    [db setKey:@"secretKey"];
    ...
}];

如果您有任何疑問,請告訴我!

有關這方面的說明,請參閱SQLCipher API頁面[1],以便在“示例1:加密明文數據庫”下使用sqlcipher_export()

[1] http://sqlcipher.net/sqlcipher-api/#sqlcipher_export

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM