FMDB and encryption

帅比萌擦擦* 提交于 2020-01-13 11:08:24

问题


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.


回答1:


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.




回答2:


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."

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



来源:https://stackoverflow.com/questions/18326225/fmdb-and-encryption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!