In the process of doing research on encrypting persistent stores for the upcoming Pro Core Data for iOS, I stumbled upon a neat recent feature that Apple calls “data protection”. In essence, if you have enabled data protection for your device as explained here, then you can tell iOS to use hardware-level encryption for any file, including the Core Data SQLite database.

This means that when creating your persistent store coordinator and the persistent store from the sqlite file, you can enable hardware-level encryption.

- (NSPersistentStoreCoordinator *)persistentStoreCoordinator {
  if (persistentStoreCoordinator_ != nil) {
    return persistentStoreCoordinator_;
  }

  persistentStoreCoordinator_ = [[NSPersistentStoreCoordinator alloc]
                        initWithManagedObjectModel:[self managedObjectModel]];

  NSURL *storeURL = [NSURL fileURLWithPath:
          [[self applicationDocumentsDirectory]
                stringByAppendingPathComponent: @"MyStore.sqlite"]];

  NSError *error = nil;
  if (![persistentStoreCoordinator_ addPersistentStoreWithType:NSSQLiteStoreType
                     configuration:nil URL:storeURL options:nil error:&error]) {
    NSLog(@"Unresolved error with store %@, %@", error, [error userInfo]);
    abort();
  }

  NSDictionary *fileAttributes = [NSDictionary
                 dictionaryWithObject:NSFileProtectionComplete
                 forKey:NSFileProtectionKey];
  if(![[NSFileManager defaultManager] setAttributes:fileAttributes
                      ofItemAtPath:[storeURL path] error: &error]) {
    NSLog(@"Unresolved error with store encryption %@, %@",
               error, [error userInfo]);
    abort();
  }

  return persistentStoreCoordinator_;
}

The trick is to set the file attribute using NSFileProtectionKey and set its value to NSFileProtectionComplete. By default it is set to NSFileProtectionNone.

Now take a minute to reflect on this and make sure you fully understand what is happening before you start jumping up and down because you got encryption for free. The data will be automatically encrypted, at the hardware level, on your device (obviously not the iOS simulator) when the device is locked. When the device is unlocked, it is automatically decrypted. So your persistent store is at best as secure as your device, but not more. If someone figures a way to crack your 4 digits lock code, you’re out of luck. And by the way, somebody has figured it out