SAMKeychain icon indicating copy to clipboard operation
SAMKeychain copied to clipboard

How to change accessibilityType for keychain entires that have already been created?

Open pdxchance opened this issue 8 years ago • 1 comments

Initially created keychain entries with the default setting which from my understanding is when device is unlocked. This has caused access problems reading from the keychain when the device is locked. We've now changed that to access always by setting this SAMKeychain.setAccessibilityType(_:) . However, what we are wondering is there a way to update the accessibilityType for existing keychain entry on users device that were initially created with a different accessibility type?

Thanks in advance.

pdxchance avatar Nov 17 '17 19:11 pdxchance

For whoever ends up in this situation, and to validate this solution, i did as follows:

pseudocode

var desiredAccessibilityType = ...

if SAMKeychain.accessibilityType == desiredAccessibilityType {
    // allready upgrated to the desiredAccessibilityType, nothing to do
    return
}

// 1. check if we have something set in keychain

var query = SAMKeychainQuery()
query.service = ...
query.accessGroup = ...

query.fetchAll(&error1)
if error1 == errSecItemNotFound {
    // Keychain is empty, nothing to do. Settings the desired AccessibilityType
    SAMKeychain.setAccessibilityType(desiredAccessibilityType);
    return
}
if error1 == errSecInteractionNotAllowed {
    // could not access keychain, aborting, call all this code later, maybe on UIApplicationProtectedDataDidBecomeAvailable
    return
}

// 2. check if we need to migrate the keychain values

var currentSavedValues = // get current saved values from keychain


SAMKeychain.setAccessibilityType(desiredAccessibilityType)

query.fetchAll(&error2)
if error2 == nil {
    // All keys have the desired AccessibilityType, nothing to do.
    return
}

if error2 == errSecItemNotFound {
    // No values found with the desired AccessibilityType need to update
    var query = SAMKeychainQuery() 
    ... // set the values from 'currentSavedValues'
    query.save(&saveError) // save internally, sets `kSecAttrAccessible` and calls `SecItemUpdate` 
   // you are done
}
// nothing to do

danielpetroianu avatar Nov 23 '18 11:11 danielpetroianu