Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FMDB and encryption

I'm using FMDB to work with sqlite and I'd prefer to avoid a dependency on SQLCipher. How can I simply leverage the DataProtection capability built into iOS? Is this possible - the only requirement is to protect the data in the event of the phone being stolen.

If the phone is unlocked with a PIN, it's fine that the user could access the DB - it's their data.

like image 909
ConfusedNoob Avatar asked Feb 15 '23 12:02

ConfusedNoob


2 Answers

Look for the line where you do databaseWithPath: (or initWithPath:), then add:

FMDatabase *db = [FMDatabase databaseWithPath:path];

NSDictionary *attributes = @{NSFileProtectionKey: NSFileProtectionCompleteUnlessOpen};
NSError *error;
BOOL success = [[NSFileManager defaultManager] setAttributes:attributes
                                                ofItemAtPath:path
                                                       error:&error];
if (!success) {
    NSLog(@"File protection failed: %@", error);
}

The possible Values for the NSFileProtectionKey key are:

  • NSFileProtectionNone: The file has no special protections associated with it. It can be read from or written to at any time.
  • NSFileProtectionComplete: The file is stored in an encrypted format on disk and cannot be read from or written to while the device is locked or booting.
  • NSFileProtectionCompleteUnlessOpen: The file is stored in an encrypted format on disk. Files can be created while the device is locked, but once closed, cannot be opened again until the device is unlocked. If the file is opened when unlocked, you may continue to access the file normally, even if the user locks the device. There is a small performance penalty when the file is created and opened, though not when being written to or read from. This can be mitigated by changing the file protection to NSFileProtectionComplete when the device is unlocked.
  • NSFileProtectionCompleteUntilFirstUserAuthentication: The file is stored in an encrypted format on disk and cannot be accessed until after the device has booted. After the user unlocks the device for the first time, your app can access the file and continue to access it even if the user subsequently locks the device.

The right type of protection may depend on the version of iOS (the last two are not available on iOS 4) and whether you use your database when the device is locked.

like image 95
eik Avatar answered Feb 19 '23 04:02

eik


By far the easiest way is to turn on Data Protection for the entire app. Go to App IDs, click "Edit" and set "Sharing and Permissions" to "Complete Protection."

enter image description here

Update Xcode with your new app id information, and from there on, it'll be handled for your app automatically.

like image 36
Rob Napier Avatar answered Feb 19 '23 04:02

Rob Napier