0

我在kSecAttrAccessibleWhenUnlocked向钥匙串添加值时设置钥匙。该文档指出:

只有当用户解锁设备时,才能访问钥匙串项中的数据。

我写了一个简单的测试应用程序,viewDidLoad方法如下:

[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

// Device (with passcode lock) is locked now

double delayInSeconds = 6.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){

    NSError * error = nil;

    [MyKeychainWrapper setKeychainObject:@"abc"
                                  forKey:@"key"
                                   error:&error];
    NSLog(@"Setting Error: %@", error); // No error logged

    NSString * value = (NSString *) [MyKeychainWrapper keychainObjectForKey:@"key"
                                                                      error:&error];
    NSLog(@"value: %@", value); // Logs ABC when the device is locked
    NSLog(@"Getting Error: %@", error); // No error logged
});

设备锁定时如何保存和读取数据?

4

1 回答 1

2

有点不清楚你是如何测试这个的,我假设你正在运行你的代码,然后按下手机上的电源按钮。按下电源按钮时不会立即发生钥匙串锁定,因此您的应用程序将能够在按下电源按钮后的一小段时间(大约 10 秒)内访问钥匙串项目。

对于 iOS;如果您在开发人员模式下在手机上运行此代码,查看控制台,您会注意到在按下手机上的电源按钮后,钥匙串实际锁定需要几秒钟。在我的 iPhone 5 上,这需要 10 秒,具体取决于正在运行的应用程序。解锁设备也是如此,钥匙串解锁需要一段时间。这是我刚刚做的一个例子;请注意,从“锁定”到“锁定”打印输出大约需要 10 秒。

May  5 14:26:20 I50 kernel[0] <Debug>: AppleKeyStore::start_keybag_locking: Device Locking..
May  5 14:26:20 I50 kernel[0] <Debug>: ALS: AppleARMBacklight::handleMessageGated - framebufferState -> 0
May  5 14:26:30 I50 UserEventAgent[14] <Error>:  LockStateNotifier aksNotificationCallback posting notification: com.apple.mobile.keybagd.lock_status
May  5 14:26:30 I50 kernel[0] <Debug>: AppleKeyStore:Sending lock change 1
May  5 14:26:30 I50 kernel[0] <Debug>: AppleKeyStore::device_state_transition: Device Locked, lockstate=1

AFAIK 苹果没有指定确切的时间,但 6 秒可能不足以让钥匙串锁定。

于 2014-05-05T12:29:28.447 回答