I am trying to use the KeychainWrapper class provided in this Apple sample code: https://developer.apple.com/library/content/samplecode/GenericKeychain/
In the sample app, the class has this init method that starts as:
- (id)initWithIdentifier: (NSString *)identifier accessGroup:(NSString *) accessGroup;
{
if (self = [super init])
{
// Begin Keychain search setup. The genericPasswordQuery leverages the special user
// defined attribute kSecAttrGeneric to distinguish itself between other generic Keychain
// items which may be included by the same application.
genericPasswordQuery = [[NSMutableDictionary alloc] init];
[genericPasswordQuery setObject:(id)kSecClassGenericPassword forKey:(id)kSecClass];
[genericPasswordQuery setObject:identifier forKey:(id)kSecAttrGeneric];
In the sample app, it uses two values for the identifier string. "Password" and "Account Number". When implementing the class in my code, I used some custom identifiers and the code did not work. The call to SecItemAdd() failed. After some testing, it seems that using values other than "Password" and "Account Number" for the identifier does not work.
Does anyone know what values are allowed and/or if it is possible to have custom identifiers for your keychain items?
Best Answer
Okay, I found the solution in this blog post Keychain duplicate item when adding password
To sum it up, the issue is that the GenericKeychain sample app uses the value stored in kSecAttrGeneric key as the identifier for the keychain item when in fact that is not what the API uses to determine a unique keychain item. The keys you need to set with unique values are the kSecAttrAccount key and/or the kSecAttrService key.
You can rewrite the initilizer of KeychainItemWrapper so you don't need to change any other code by changing these lines:
Change:
to:
and change:
to:
Or, you could do what I did and write a new initilizer that takes both of the identifying keys:
Edit: For people using ARC (you should be nowadays) check nycynik's answer for all the correct bridging notation
Hope this helps someone else out!