Search code examples
iphonekeychain

help with a useful implementation of keychain on an iphone app


Users have requested a "lock" on my iphone app, which makes good sense as it contains private information. I believe encryption of the data goes above and beyond what people expect on a phone, so my goal is simply to prevent unintended access to the app. My plan is to use keychain to store the password using my app name as the ServiceName.

My concern is what happens for users if they lose/forget the password they typed in. Is there something I can do programatically to allow a user reset? Would deleting the app delete the keychain for the app?

I don't want to collect user emails. (Well I do, but I don't want this to be the justification.) And don't want the user to be permanently locked out of the app if they've lost the passsword.


Solution

  • On the iPhone there is just a single keychain database, and there is no possibility to add a custom, application specific, keychain (as you can do on a Mac instead). By default, the keychain items you add to the keychain in your app are only available to your app. There is no documentation (to the best of my knowledge) stating the behavior occurring when the user deletes your app: may be iOS 4.1 deletes the app keychain items, may be it does leave them in the keychain.

    Depending on how you stored the user's password, you may be able to retrieve it. For instance, if you stored a tag related to your application along with the user's password in a kSecAttrApplicationTag, then you may search for your exact tag in the keychain using the

    OSStatus SecItemCopyMatching (
       CFDictionaryRef query,
       CFTypeRef *result
    );
    

    function. If the search is successful, then you may retrieve the password from the returned dictionary using the kSecValueData key or, if you prefer, you can even change it using

    OSStatus SecItemUpdate (
       CFDictionaryRef query,
       CFDictionaryRef attributesToUpdate
    );
    

    For additional information, see the keychain reference and the Keychain Services Tasks for iOS documentation.