2010-09-10 141 views
0

我一直在試圖加密/解密我的iPhone項目中的sqlite數據庫。我能夠通過使用reKey方法來加密數據庫。但我無法解密它。 我已將我的sqlite.db文件保存在一個文件夾中。目前正在模擬器上嘗試它。sqlite加密/解密+ sqlcipher + iPhone

代碼片段:

[[SQLiteDB sharedSQLiteDB] open:<path to the folder> withKey:@""]; 

[[SQLiteDB sharedSQLiteDB] reKey:@"abc"]; 

[[SQLiteDB sharedSQLiteDB] close]; 

[[SQLiteDB sharedSQLiteDB] open:<path to the folder> withKey:@"abc"]; 

[[SQLiteDB sharedSQLiteDB] reKey:@""]; 

.....

- (BOOL)open:(NSString *)path withKey:(NSString *)masterKey { 

    if (sqlite3_open([path fileSystemRepresentation], &_db) != SQLITE_OK) { 
     NSLog(@"SQLite Opening Error: %s", sqlite3_errmsg(_db)); 
     return NO; 
    } 

    if(masterKey) 
     sqlite3_exec(_db, [[NSString stringWithFormat:@"PRAGMA key = '%@'", masterKey] UTF8String], NULL, NULL, NULL); 

    if (sqlite3_exec(_db, (const char*) "SELECT count(*) FROM sqlite_master", NULL, NULL, NULL) != SQLITE_OK) 
    { 
     [self close]; 
     NSLog(@"SQLite Key Error!"); 
     return NO; 
    } 

    filePath = [path retain]; 
    return YES; 
} 

......

- (void)reKey:(NSString *)masterKey 
{ 
    sqlite3_exec(_db, [[NSString stringWithFormat:@"PRAGMA rekey = '%@'", masterKey] UTF8String], NULL, NULL, NULL); 

} 

我已閱讀職位有關此主題的sqlcipher谷歌團體,但我無法解密它。任何幫助將不勝感激。

回答

2

從郵件列表寄託:

如果你想利用現有的非加密數據庫,加密,然後解密回來,我們推薦的方法是不使用密鑰更新,而是要使用連接數據庫在標準和sqlcipher數據庫之間複製數據。有更多的信息,在這裏一個具體的例子:

http://www.zetetic.net/blog/2009/12/29/how-to-encrypt-a-plaintext-sqlite-database-to-use-sqlcipher/

相反,如果你只是想用sqlcipher於一般的數據(即沒有從預先存在的數據庫轉換)加密,那麼你只需要使用sqlite3_key。你基本上只是打開數據庫,提供密鑰,然後進行SQL調用。沒有單獨的加密/解密步驟 - 所有這些都是由sqlcipher代碼實時處理的。在你之前發佈的代碼中,你根本不會調用rekey。每次打開數據庫時,都會調用PRAGMA鍵,然後運行快速檢查以確保sqlite_master可讀。

+0

謝謝,第一種方法在我的情況下工作。 – random 2010-09-15 09:31:14