iOS Core Data Encryption

How can I encrypt CoreData contents on an iPhone

You can encrypt individual properties in your Core Data model entities by making them transformable properties, then creating an NSValueTransformer subclass which will encrypt and decrypt the data for that property. While this is not the whole-database decryption that you're looking for, it will have a much lower memory footprint than decrypting an entire database into memory. Additionally, it will allow the decryption to be done lazily, rather than all up front, so your application will load much faster. Depending on the encryption used, I would even expect that the on-disk data accesses for loading each entity would be slower than the decryption process for the properties, so you won't see that much of a performance penalty when accessing the properties.

Transformable properties like this are very easy to use, because you read and write to them as normal, while the encryption / decryption goes on behind the scenes.

How to enable Core Data Encryption on SwiftUI?

The NSPersistentContainer has an array of persistentStoreDescriptions, which you can modify before calling container.loadPersistentStores. In fact, you already do this to change the store’s URL if inMemory is true.

So to set the file protection option:

container = NSPersistentContainer(name: "TharmaTrack")
container.persistentStoreDescriptions.first!.setOption(FileProtectionType.complete as NSObject,
forKey: NSPersistentStoreFileProtectionKey)

Do I need to encrypt iOS Core Data?

You have a few options.

  1. Assume the user has their passcode enabled, and know that that means the DB is encrypted when the device is locked. For some cases, this is enough.

  2. Encrypt the Core Data using Encrypted Core Data. FYI, this does work, but it has lots of limitations and bugs. We used it in an enterprise app and I regret using it.

  3. Move away from Core Data to SQLite with SQLCipher. This is what I prefer now.

Bear in mind that you still have to deal with the DB key if you do per-app encryption. You can do this in a number of ways.

  1. In many cases, you can just store the key in the Keychain and that's sufficient.
  2. You can also require passcode/Touch ID/Face ID when launching your app/accessing the keychain item
  3. Finally, you cal require the user to enter the passphrase
  4. Regardless of your choice, use a key-derivation function such as PBKDF2 ~100,000 times to make brute forcing harder. Never store the actual DB key (which is derived).


Related Topics



Leave a reply



Submit