core-data – NSFileProtectionComplete不加密核心数据文件

core-data – NSFileProtectionComplete不加密核心数据文件,第1张

概述我正在使用 Xcode 7.3 for iOS 9.3来尝试加密Core Data文件.我正在尝试使用NSPersistentStoreFileProtectionKey并将其设置为NSFileProtectionComplete以启用加密.它由于某种原因无法工作,我总能看到应用程序生成的.sqlite文件,并浏览sqlitebrowser或iexplorer中的内容.这是我的代码: lazy v 我正在使用 Xcode 7.3 for iOS 9.3来尝试加密Core Data文件.我正在尝试使用NSPersistentStorefileProtectionKey并将其设置为NSfileProtectionComplete以启用加密.它由于某种原因无法工作,我总能看到应用程序生成的.sqlite文件,并浏览sqlitebrowser或IExplorer中的内容.这是我的代码:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {    // The persistent store coordinator for the application. This implementation creates and returns a coordinator,having added the store for the application to it. This property is optional since there are legitimate error conditions that Could cause the creation of the store to fail.    // Create the coordinator and store    let coordinator = NSPersistentStoreCoordinator(managedobjectModel: self.managedobjectModel)    let url = self.applicationdocumentsDirectory.URLByAppendingPathComponent("SingleVIEwCoreData.sqlite")    var failureReason = "There was an error creating or loading the application's saved data."    let dict: [NSObject : AnyObject] = [        NSPersistentStorefileProtectionKey        : NSfileProtectionComplete    ]    do {        try coordinator.addPersistentStoreWithType(NSsqliteStoreType,configuration: nil,URL: url,options: dict)    } catch {        // Report any error we got.        var dict = [String: AnyObject]()        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"        dict[NSLocalizedFailurereasonerrorKey] = failureReason        dict[NSUnderlyingErrorKey] = error as NSError        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN",code: 9999,userInfo: dict)        // Replace this with code to handle the error appropriately.        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipPing application,although it may be useful during development.        NSLog("Unresolved error \(wrappedError),\(wrappedError.userInfo)")        abort()    }    do {        let url = self.applicationdocumentsDirectory.URLByAppendingPathComponent("SingleVIEwCoreData.sqlite")        try NSfileManager.defaultManager().setAttributes([NSfileProtectionKey : NSfileProtectionComplete],ofItemAtPath: url.path!)    } catch {    }    do {        let url = self.applicationdocumentsDirectory.URLByAppendingPathComponent("SingleVIEwCoreData.sqlite-wal")        try NSfileManager.defaultManager().setAttributes([NSfileProtectionKey : NSfileProtectionComplete],ofItemAtPath: url.path!)        //            try print(NSfileManager.defaultManager().attributesOffileSystemForPath(String(url)))    } catch {    }    do {        let url = self.applicationdocumentsDirectory.URLByAppendingPathComponent("SingleVIEwCoreData.sqlite-shm")        try NSfileManager.defaultManager().setAttributes([NSfileProtectionKey : NSfileProtectionComplete],ofItemAtPath: url.path!)        //            try print(NSfileManager.defaultManager().attributesOffileSystemForPath(String(url)))    } catch {    }    return coordinator}()

我还在“功能”中为我的目标启用了数据保护.我已从Apple Developer门户重新生成配置文件,并将其与Enabled Data Protection一起使用.

我还使用以下代码来检查.sqlite,.sqlite-wal和.sqlite-shm文件的文件属性.正确为所有3个NSfileProtectionKey设置了它.

func checkProtectionForLocalDb(atDir : String){    let fileManager = NSfileManager.defaultManager()    let enumerator: NSDirectoryEnumerator = fileManager.enumeratorAtPath(atDir)!    for path in enumerator {        let attr : NSDictionary = enumerator.fileAttributes!        print(attr)    }}

我还尝试禁用日记模式以防止创建-wal和-shm文件.但我仍然可以阅读.sqlite文件.即使属性读取NSfileProtectionComplete.

如Apple文档Apple Docs“使用磁盘加密保护数据”中所述,我尝试检查变量protectedDataAvailable的值是否发生了变化,如下面的代码所示

public func applicationDIDEnterBackground(application: UIApplication) {    // Use this method to release shared resources,save user data,invalIDate timers,and store enough application state information to restore your application to its current state in case it is terminated later.    // If your application supports background execution,this method is called instead of applicationWillTerminate: when the user quits.    NSThread.sleepForTimeInterval(10)    sleep(10)    let dataAvailable : Bool = UIApplication.sharedApplication().protectedDataAvailable    print("Protected Data Available : " + String(dataAvailable))}

如果我在没有延迟的情况下检查该值,则将其设置为true,但在添加延迟后将其设置为false.然而,这是一种令人鼓舞的事情,当我下载容器以显示内容时,它仍然具有.sqlite文件,在sqlitebrowser中打开时仍显示内容.

好的,我终于理解了这一点.

使用Xcode 7.3.1 ..

启用文件保护

>使用应用目标上的功能选项卡启用文件保护
>如果您不想使用默认的NSfileProtectionComplete,请在应用程序ID下的开发人员门户中更改此设置
>确保XCode具有此创建的新配置文件.
>为了保护您的应用创建的文件,就是这样.
>要保护Core Data,您需要将NSPersistentStorefileProtectionKey:NSfileProtectionComplete选项添加到持久性存储中.

例:

var options: [NSObject : AnyObject] = [NSMigratePersistentStoresautomaticallyOption: true,NSPersistentStorefileProtectionKey: NSfileProtectionComplete,NSInferMapPingModelautomaticallyOption: true]    do {        try coordinator!.addPersistentStoreWithType(NSsqliteStoreType,options: options)

测试文件保护

我无法使用连接到计算机的非越狱设备对此进行测试.每次以这种方式访问​​设备的尝试都要求我“信任”计算机,我相信可信任的计算机始终能够读取手机的数据(“可信计算机可以与您的iOS设备同步,创建备份,以及访问设备的照片,视频,联系人和其他内容“ – https://support.apple.com/en-us/HT202778).我认为SO引用此技术的其他答案对于更新版本的iOS不再有效.实际上,我总是能够使用XCode下载容器并使用iPhone Explorer查看应用程序的数据.那么如何测试……

1 – 通过从命令行在.app文件上运行以下命令,创建存档并确保其具有正确的权利:

codesign -d --enTitlements :- <path_to_app_binary>

您应该看到代表您的数据保护级别的键/值对.在这个例子中,NSfileProtectionComplete:

<key>com.apple.developer.default-data-protection</key><string>NSfileProtectionComplete</string>

另外,我使用以下两种技术来确保数据保护确实有效.它们都需要更改代码.

2 – 添加一些代码以验证是否在文件和/或核心数据存储上设置了正确的NSfileProtectionKey:

NSfileManager.defaultManager().attributesOfItemAtPath(dbPath.path!)

如果我在我的一个文件上打印出来,我会得到:

["NSfileCreationDate": 2016-10-14 02:06:39 +0000,"NSfileGroupOwnerAccountname": mobile,"NSfileType": NSfileTypeRegular,"NSfileSystemNumber": 16777218,"NSfileOwnerAccountname": mobile,"NSfileReferenceCount": 1,"NSfileModificationDate": 2016-10-14 02:06:39 +0000,"NSfileExtensionHIDden": 0,"NSfileSize": 81920,"NSfileGroupOwnerAccountID": 501,"NSfileOwnerAccountID": 501,"NSfilePosixPermissions": 420,"NSfileProtectionKey": NSfileProtectionComplete,"NSfileSystemfileNumber": 270902]

注意“NSfileProtectionKey”:NSfileProtectionComplete对.

3 – 修改以下代码并将其连接到应用程序中的某个按钮.

@IBAction func settingbuttontouch(sender: AnyObject) {        updateTimer = NSTimer.scheduledTimerWithTimeInterval(0.5,target: self,selector: #selector(TabbedOvervIEwVIEwController.runTest),userInfo: nil,repeats: true)        registerBackgroundTask()}var backgroundTask: uibackgroundtaskIDentifIEr = uibackgroundtaskInvalIDvar updateTimer: NSTimer?func registerBackgroundTask() {    backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler {        [uNowned self] in        self.endBackgroundTask()    }    assert(backgroundTask != uibackgroundtaskInvalID)}func endBackgroundTask() {    NSLog("Background task ended.")    UIApplication.sharedApplication().endBackgroundTask(backgroundTask)    backgroundTask = uibackgroundtaskInvalID}func runtest() {    switch UIApplication.sharedApplication().applicationState {    case .Active:        NSLog("App is active.")        checkfiles()    case .Background:        NSLog("App is backgrounded.")        checkfiles()    case .Inactive:        break    }}func checkfiles() {    //attempt to access a protected resource,i.e. a core data store or file}

当您点击按钮时,此代码每隔0.5秒开始执行checkfiles方法.这应该在应用程序的前台或后台无限期运行 – 直到您锁定手机.此时它应该在大约10秒后可靠地失败 – 完全如NSfileProtectionComplete的描述中所述.

总结

以上是内存溢出为你收集整理的core-data – NSFileProtectionComplete不加密核心数据文件全部内容,希望文章能够帮你解决core-data – NSFileProtectionComplete不加密核心数据文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1043395.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-24
下一篇 2022-05-24

发表评论

登录后才能评论

评论列表(0条)

保存