Search code examples
iosobjective-cstoragekeychain

iOS Key Chain alternative without possibility to restore on another device


Is it possible to store some information on iOS that will not be deleted when the app is deleted (like Keychain) and also cannot be restored to another device?

As i understand - Key Chain will be restored to another device if you select an encrypted backup option. Does iOS keychain storage persist when restoring an app to a new device?

So is it somehow possible to preserve some data - after the app is deleted (to read it after the reinstall) and for it only be avalible on the device it was added / created.


Solution

  • There are these options:

    kSecAttrAccessibleAlwaysThisDeviceOnly
    kSecAttrAccessibleWhenUnlockedThisDeviceOnly
    kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
    

    From the docs:

    [...] Items with this attribute do not migrate to a new device. [...]

    I think they are exactly what you need. They are explained well in this WWDC talk:

    https://developer.apple.com/videos/wwdc/2014/#711

    Example usage from the above talk:

    SecAccessControlRef sacObject =
    SecAccessControlCreateWithFlags(kCFAllocatorDefault,
       kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly,
       kSecAccessControlUserPresence, &error);
    
    NSData* secret = [@"top secret" dataWithEncoding:NSUTF8StringEncoding];
    NSDictionary *query = @{
       (id)kSecClass: (id)kSecClassGenericPassword,
       (id)kSecAttrService: @"myservice",
       (id)kSecAttrAccount: @"account name here",
       (id)kSecValueData: secret};
    
    OSStatus status =  SecItemAdd((CFDictionaryRef)query, nil);
    

    See also: https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/index.html#//apple_ref/doc/constant_group/Keychain_Item_Accessibility_Constants