2010-09-10 168 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