在公司產品上線前, 準備把數據庫加密掉, 原本是幾行代碼的事情, 倒騰了幾個小時......git
網上大多數方法的作法是, 直接修改FMDatabase.h
方法, 我認爲直接修改第三方庫的源碼, 是不科學的, 個人作法是建立新類, 繼承自FMDatabase, 重寫相應的方法, 在須要加密的地方, 添加加密用的語句.github
原來項目中已經經過cocoapod集成了FMDB
框架. 剛開始個人作法是, 在Profile上直接加上pod 'FMDB/SQLCipher' #數據庫加密
, 這時候Profile中同時包含 pod 'FMDB' #數據庫`` pod 'FMDB/SQLCipher'
, 安裝以後, 無論怎麼測試, 老是沒法讀寫數據庫, 耗了好長時間, 最終發現, 刪除 ``pod 'FMDB'` 以後, 就能夠正常讀寫了......sql
cocoapod集成SQLCipher時候, Profile加入 'FMDB/SQLCipher' 便可!!數據庫
#pragma mark - 對FMDataBase加密, 使用 SQLCipher, 經過重載方法 實現加密 #import "sqlite3.h" @implementation FMCipherDataBase static NSString *DB_SECRETKEY = @"123456"; + (instancetype)databaseWithPath:(NSString *)inPath cipherKey:(NSString *)cipherKey { FMCipherDataBase *database = [super databaseWithPath:inPath]; DB_SECRETKEY = cipherKey; return database; } - (const char*)sqlitePath { if (!_databasePath) { return ":memory:"; } if ([_databasePath length] == 0) { return ""; // this creates a temporary database (it's an sqlite thing). } return [_databasePath fileSystemRepresentation]; } - (BOOL)open { if (_db) { return YES; } int err = sqlite3_open([self sqlitePath], (sqlite3**)&_db ); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } else { [self setKey:DB_SECRETKEY]; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } return YES; } - (BOOL)openWithFlags:(int)flags vfs:(NSString *)vfsName { #if SQLITE_VERSION_NUMBER >= 3005000 if (_db) { return YES; } int err = sqlite3_open_v2([self sqlitePath], (sqlite3**)&_db, flags, [vfsName UTF8String]); if(err != SQLITE_OK) { NSLog(@"error opening!: %d", err); return NO; } else { [self setKey:DB_SECRETKEY]; } if (_maxBusyRetryTimeInterval > 0.0) { // set the handler [self setMaxBusyRetryTimeInterval:_maxBusyRetryTimeInterval]; } return YES; #else NSLog(@"openWithFlags requires SQLite 3.5"); return NO; #endif } @end