对于那些寻找关于如何做到这一点简单的教程中,我能创造一个:http://www.guilmo.com/fmdb-with-sqlcipher-tutorial/
但最重要的部分,打开现有的DB和连接一个新的加密的。然后在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查询的数据库和密钥设置2个参数。数据库应该是完整路径到您要创建的加密数据库,在这种情况下,字符串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"];
...
}];
让我知道如果您有任何问题!
1.是2.是的,它的简单只是覆盖“打开”方法来加密/解密您的数据库。 – CarlJ 2012-04-11 13:15:00
谢谢你meccan。会试试这个。 – 2012-04-11 20:55:26