- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDir = [documentPaths objectAtIndex:0]; self.databasePath = [documentDir stringByAppendingPathComponent:@"sqmple.sqlite"]; [self createAndCheckDatabase]; return YES; } -(void) createAndCheckDatabase { BOOL success; NSFileManager *fileManager = [NSFileManager defaultManager]; success = [fileManager fileExistsAtPath:self.databasePath]; if (success) return; // If file exists, don't do anything // if file does not exist, make a copy of the one in the Resources folder NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"sample.sqlite"]; // File path [fileManager copyItemAtPath:databasePathFromApp toPath:self.databasePath error:nil]; // Make a copy of the file in the Documents folder // Set the new encrypted database path to be in the Documents Folder NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentDir = [documentPaths objectAtIndex:0]; NSString *encryptedDatabasePath = [documentDir stringByAppendingPathComponent:@"encrypted.sqlite"]; NSString *key = @"PassKey"; // SQL Query. NOTE THAT DATABASE IS THE FULL PATH NOT ONLY THE NAME const char* sqlQ = [[NSString stringWithFormat:@"ATTACH DATABASE '%@' AS encrypted KEY '%@';", encryptedDatabasePath, key] 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"]; }
- (FMDatabase *)openWriteableDatabase { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"encrypted.sqlite"]; FMDatabase* database = [FMDatabase databaseWithPath:writableDBPath]; [database open]; NSString *key = @"PassKey"; [database setKey:key]; return database; }
NSString *newKey = @"NewPassKey"; [database rekey:newKey];
Source: https://habr.com/ru/post/222487/