Skip to content

Instantly share code, notes, and snippets.

@dhoerl
Last active April 4, 2023 08:15
Show Gist options
  • Save dhoerl/1170641 to your computer and use it in GitHub Desktop.
Save dhoerl/1170641 to your computer and use it in GitHub Desktop.
KeychainItemWrapper ARCified. Added the ability to manage a dictionary in place of just a string - the #define PASSWORD_USES_DATA in the .m file switches the mode.
/*
File: KeychainItemWrapper.h
Abstract:
Objective-C wrapper for accessing a single keychain item.
Version: 1.2 - ARCified
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#import <UIKit/UIKit.h>
/*
The KeychainItemWrapper class is an abstraction layer for the iPhone Keychain communication. It is merely a
simple wrapper to provide a distinct barrier between all the idiosyncracies involved with the Keychain
CF/NS container objects.
*/
@interface KeychainItemWrapper : NSObject
// Designated initializer.
- (id)initWithIdentifier: (NSString *)identifier accessGroup:(NSString *)accessGroup;
- (void)setObject:(id)inObject forKey:(id)key;
- (id)objectForKey:(id)key;
// Initializes and resets the default generic keychain item data.
- (void)resetKeychainItem;
@end
/*
File: KeychainItemWrapper.m
Abstract:
Objective-C wrapper for accessing a single keychain item.
Version: 1.2 - ARCified
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2010 Apple Inc. All Rights Reserved.
*/
#define PASSWORD_USES_DATA
#import "KeychainItemWrapper.h"
#import <Security/Security.h>
/*
These are the default constants and their respective types,
available for the kSecClassGenericPassword Keychain Item class:
kSecAttrAccessGroup - CFStringRef
kSecAttrCreationDate - CFDateRef
kSecAttrModificationDate - CFDateRef
kSecAttrDescription - CFStringRef
kSecAttrComment - CFStringRef
kSecAttrCreator - CFNumberRef
kSecAttrType - CFNumberRef
kSecAttrLabel - CFStringRef
kSecAttrIsInvisible - CFBooleanRef
kSecAttrIsNegative - CFBooleanRef
kSecAttrAccount - CFStringRef
kSecAttrService - CFStringRef
kSecAttrGeneric - CFDataRef
See the header file Security/SecItem.h for more details.
*/
@interface KeychainItemWrapper (PrivateMethods)
/*
The decision behind the following two methods (secItemFormatToDictionary and dictionaryToSecItemFormat) was
to encapsulate the transition between what the detail view controller was expecting (NSString *) and what the
Keychain API expects as a validly constructed container class.
*/
- (NSMutableDictionary *)secItemFormatToDictionary:(NSDictionary *)dictionaryToConvert;
- (NSMutableDictionary *)dictionaryToSecItemFormat:(NSDictionary *)dictionaryToConvert;
// Updates the item in the keychain, or adds it if it doesn't exist.
- (void)writeToKeychain;
@end
@implementation KeychainItemWrapper
{
NSMutableDictionary *keychainItemData; // The actual keychain item data backing store.
NSMutableDictionary *genericPasswordQuery; // A placeholder for the generic keychain item query used to locate the item.
}
- (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:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
[genericPasswordQuery setObject:identifier forKey:(__bridge id)kSecAttrGeneric];
// The keychain access group attribute determines if this item can be shared
// amongst multiple apps whose code signing entitlements contain the same keychain access group.
if (accessGroup != nil)
{
#if TARGET_IPHONE_SIMULATOR
// Ignore the access group if running on the iPhone simulator.
//
// Apps that are built for the simulator aren't signed, so there's no keychain access group
// for the simulator to check. This means that all apps can see all keychain items when run
// on the simulator.
//
// If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
// simulator will return -25243 (errSecNoAccessForItem).
#else
[genericPasswordQuery setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup];
#endif
}
// Use the proper search constants, return only the attributes of the first match.
[genericPasswordQuery setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[genericPasswordQuery setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes];
NSDictionary *tempQuery = [NSDictionary dictionaryWithDictionary:genericPasswordQuery];
CFMutableDictionaryRef outDictionary = NULL;
if (!SecItemCopyMatching((__bridge CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) == noErr)
{
// Stick these default values into keychain item if nothing found.
[self resetKeychainItem];
// Add the generic attribute and the keychain access group.
[keychainItemData setObject:identifier forKey:(__bridge id)kSecAttrGeneric];
if (accessGroup != nil)
{
#if TARGET_IPHONE_SIMULATOR
// Ignore the access group if running on the iPhone simulator.
//
// Apps that are built for the simulator aren't signed, so there's no keychain access group
// for the simulator to check. This means that all apps can see all keychain items when run
// on the simulator.
//
// If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
// simulator will return -25243 (errSecNoAccessForItem).
#else
[keychainItemData setObject:accessGroup forKey:(__bridge id)kSecAttrAccessGroup];
#endif
}
}
else
{
// load the saved data from Keychain.
keychainItemData = [self secItemFormatToDictionary:(__bridge NSDictionary *)outDictionary];
}
if(outDictionary) CFRelease(outDictionary);
}
return self;
}
- (void)setObject:(id)inObject forKey:(id)key
{
if (inObject == nil) return;
id currentObject = [keychainItemData objectForKey:key];
if (![currentObject isEqual:inObject])
{
[keychainItemData setObject:inObject forKey:key];
[self writeToKeychain];
}
}
- (id)objectForKey:(id)key
{
return [keychainItemData objectForKey:key];
}
- (void)resetKeychainItem
{
if (!keychainItemData)
{
keychainItemData = [[NSMutableDictionary alloc] init];
}
else if (keychainItemData)
{
NSMutableDictionary *tempDictionary = [self dictionaryToSecItemFormat:keychainItemData];
#ifndef NS_BLOCK_ASSERTIONS
OSStatus junk =
#endif
SecItemDelete((__bridge CFDictionaryRef)tempDictionary);
NSAssert( junk == noErr || junk == errSecItemNotFound, @"Problem deleting current dictionary." );
}
// Default attributes for keychain item.
[keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrAccount];
[keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrLabel];
[keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrDescription];
// Default data for keychain item.
#ifndef PASSWORD_USES_DATA
[keychainItemData setObject:@"" forKey:(__bridge id)kSecValueData];
#else
[keychainItemData setObject:[NSData data] forKey:(__bridge id)kSecValueData];
#endif
}
- (NSMutableDictionary *)dictionaryToSecItemFormat:(NSDictionary *)dictionaryToConvert
{
// The assumption is that this method will be called with a properly populated dictionary
// containing all the right key/value pairs for a SecItem.
// Create a dictionary to return populated with the attributes and data.
NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionaryToConvert];
// Add the Generic Password keychain item class attribute.
[returnDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
// Convert the NSString to NSData to meet the requirements for the value type kSecValueData.
// This is where to store sensitive data that should be encrypted.
#ifndef PASSWORD_USES_DATA
// orig
NSString *passwordString = [dictionaryToConvert objectForKey:(__bridge id)kSecValueData];
[returnDictionary setObject:[passwordString dataUsingEncoding:NSUTF8StringEncoding] forKey:(__bridge id)kSecValueData];
#else
// DFH
id val = [dictionaryToConvert objectForKey:(__bridge id)kSecValueData];
if([val isKindOfClass:[NSString class]]) {
val = [(NSString *)val dataUsingEncoding:NSUTF8StringEncoding];
}
[returnDictionary setObject:val forKey:(__bridge id)kSecValueData];
#endif
return returnDictionary;
}
- (NSMutableDictionary *)secItemFormatToDictionary:(NSDictionary *)dictionaryToConvert
{
// The assumption is that this method will be called with a properly populated dictionary
// containing all the right key/value pairs for the UI element.
// Create a dictionary to return populated with the attributes and data.
NSMutableDictionary *returnDictionary = [NSMutableDictionary dictionaryWithDictionary:dictionaryToConvert];
// Add the proper search key and class attribute.
[returnDictionary setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[returnDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
// Acquire the password data from the attributes.
CFDataRef passwordData = NULL;
if (SecItemCopyMatching((__bridge CFDictionaryRef)returnDictionary, (CFTypeRef *)&passwordData) == noErr)
{
// Remove the search, class, and identifier key/value, we don't need them anymore.
[returnDictionary removeObjectForKey:(__bridge id)kSecReturnData];
#ifndef PASSWORD_USES_DATA
// Add the password to the dictionary, converting from NSData to NSString.
NSString *password = [[NSString alloc] initWithBytes:[(__bridge NSData *)passwordData bytes] length:[(__bridge NSData *)passwordData length]
encoding:NSUTF8StringEncoding];
#else
NSData *password = (__bridge_transfer NSData *)passwordData;
passwordData = NULL;
#endif
[returnDictionary setObject:password forKey:(__bridge id)kSecValueData];
}
else
{
// Don't do anything if nothing is found.
NSAssert(NO, @"Serious error, no matching item found in the keychain.\n");
}
if(passwordData) CFRelease(passwordData);
return returnDictionary;
}
- (void)writeToKeychain
{
CFDictionaryRef attributes = NULL;
NSMutableDictionary *updateItem = nil;
OSStatus result;
if (SecItemCopyMatching((__bridge CFDictionaryRef)genericPasswordQuery, (CFTypeRef *)&attributes) == noErr)
{
// First we need the attributes from the Keychain.
updateItem = [NSMutableDictionary dictionaryWithDictionary:(__bridge NSDictionary *)attributes];
// Second we need to add the appropriate search key/values.
[updateItem setObject:[genericPasswordQuery objectForKey:(__bridge id)kSecClass] forKey:(__bridge id)kSecClass];
// Lastly, we need to set up the updated attribute list being careful to remove the class.
NSMutableDictionary *tempCheck = [self dictionaryToSecItemFormat:keychainItemData];
[tempCheck removeObjectForKey:(__bridge id)kSecClass];
#if TARGET_IPHONE_SIMULATOR
// Remove the access group if running on the iPhone simulator.
//
// Apps that are built for the simulator aren't signed, so there's no keychain access group
// for the simulator to check. This means that all apps can see all keychain items when run
// on the simulator.
//
// If a SecItem contains an access group attribute, SecItemAdd and SecItemUpdate on the
// simulator will return -25243 (errSecNoAccessForItem).
//
// The access group attribute will be included in items returned by SecItemCopyMatching,
// which is why we need to remove it before updating the item.
[tempCheck removeObjectForKey:(__bridge id)kSecAttrAccessGroup];
#endif
// An implicit assumption is that you can only update a single item at a time.
#ifndef NDEBUG
result =
#endif
SecItemUpdate((__bridge CFDictionaryRef)updateItem, (__bridge CFDictionaryRef)tempCheck);
NSAssert( result == noErr, @"Couldn't update the Keychain Item." );
}
else
{
// No previous item found; add the new one.
result = SecItemAdd((__bridge CFDictionaryRef)[self dictionaryToSecItemFormat:keychainItemData], NULL);
NSAssert( result == noErr, @"Couldn't add the Keychain Item." );
}
if(attributes) CFRelease(attributes);
}
@end
@xcvista
Copy link

xcvista commented May 23, 2013

@yogeshbh You actually can read the header files of GNUstep libobjc2 to get an idea what is under the hood of Objective-C runtime - GNUstep libobjc2 is code compatible with Apple's.

@Geremp
Copy link

Geremp commented Jan 5, 2014

Hi,

I have an issue about keychainwrapper:

  • On the simulator, my app works.
  • On my device, app crash when i try to access to the keychain (Iphone 4S, IOS 7.0.4)
    the console show me this :

Jan 5 04:22:46 GeremIphone securityd[162] : securityd_xpc_dictionary_handler Crossfit Lyon[480] copy_matching The operation couldn’t be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements)
Jan 5 04:22:46 GeremIphone Crossfit Lyon[480] : SecOSStatusWith error:[-34018] The operation couldn’t be completed. (OSStatus error -34018 - Remote error : The operation couldn‚Äôt be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements))
Jan 5 04:22:46 GeremIphone securityd[162] : securityd_xpc_dictionary_handler Crossfit Lyon[480] add The operation couldn’t be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements)
Jan 5 04:22:46 GeremIphone Crossfit Lyon[480] : SecOSStatusWith error:[-34018] The operation couldn’t be completed. (OSStatus error -34018 - Remote error : The operation couldn‚Äôt be completed. (OSStatus error -34018 - client has neither application-identifier nor keychain-access-groups entitlements))
Jan 5 04:22:46 GeremIphone Crossfit Lyon[480] : *** Assertion failure in -[KeychainItemWrapper writeToKeychain], /Volumes/Donnees/gerem/Desktop/Apps Dev Iphone/test/Crossfit Lyon/Crossfit Lyon/KeychainItemWrapper.m:328
Jan 5 04:22:46 GeremIphone Crossfit Lyon[480] : *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.'
*** First throw call stack:
(0x2fd96f4b 0x3a1d76af 0x2fd96e25 0x3073efe3 0x658d3 0x64c97 0x63aab 0x5b9ad 0x3253e713 0x3253e6b3 0x3253e691 0x3252a11f 0x3253e107 0x3253ddd9 0x32538e65 0x3250e79d 0x3250cfa3 0x2fd62183 0x2fd61653 0x2fd5fe47 0x2fccac27 0x2fccaa0b 0x349f1283 0x3256e049 0x5c2e9 0x3a6dfab7)
Jan 5 04:22:46 GeremIphone ReportCrash[481] : MS:Notice: Injecting: (null) ReportCrash
Jan 5 04:22:46 GeremIphone ReportCrash[481] : ReportCrash acting against PID 480
Jan 5 04:22:47 GeremIphone ReportCrash[481] : Formulating crash report for process Crossfit Lyon[480]
Jan 5 04:22:47 GeremIphone com.apple.launchd1 : (UIKitApplication:jeremieperera.Crossfit-Lyon[0x7282]) Job appears to have crashed: Abort trap: 6
Jan 5 04:22:47 GeremIphone backboardd[33] : Application 'UIKitApplication:jeremieperera.Crossfit-Lyon[0x7282]' exited abnormally with signal 6: Abort trap: 6

Have you any idea about fix this ?

I initiate my object :

keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:@"CrossfitLyonLogin" accessGroup:nil];

@EncomCTO
Copy link

geremp same issue here. I'm still trying to find a solution

@HaifaCarina
Copy link

Worked like magic! Thank you for sharing this!

@dlynns
Copy link

dlynns commented Nov 10, 2014

Thanks for the code, saved me a bunch of time.

@peekpeek
Copy link

Is this code still necessary to store items in the keychain in iOS 8? Or is there an easier to store items in teh keychain?

@mufeidie
Copy link

For those who received 25243 error or "Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.'"

25243 is related to keychain permission and you won't see this error in simulator because simulator app wasn't signed.

In my case, i set the keychain access group in Target->Keychain sharing, then i directly accessed the keychain with the group name. This is wrong because the actual keychain access group should be $(AppIdentifierPrefix)whatever.you.set. You can find it from entitlements.plist.

@johne
Copy link

johne commented Sep 2, 2015

thanks for converting this...

i am having a problem... when i build an ad hoc distrib of this and install it on my ipad running 8.1.1 (though i'm guessing the fact that it is an ipad isn't a factor here)...

it is running fine other other devices... and it is running fine as a debug build on the ipad....

any ideas?

i'm getting an exception in the init method on line 164 (the line where you release outDictionary):
Incident Identifier: 9078F719-1817-4F36-922A-18185635EF7F
CrashReporter Key: 476204eaca3c41ca42ac4450bdd98cd0783a9298
Hardware Model: iPad2,1
Process: xxx
Path: xxx
Identifier: xxx
Version: 3.0.3 (3.0.3)
Code Type: ARM (Native)
Parent Process: launchd [1]

Date/Time: 2015-09-02 15:36:07.182 -0700
Launch Time: 2015-09-02 15:36:06.634 -0700
OS Version: iOS 8.1.1 (12B435)
Report Version: 105

Exception Type: EXC_BREAKPOINT (SIGTRAP)
Exception Codes: 0x0000000000000001, 0x000000000000defe
Triggered by Thread: 0

Thread 0 name: Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0 CoreFoundation 0x272d9aae CFRelease + 1266
1 0x000d2fe6 -KeychainItemWrapper initWithIdentifier:accessGroup:

@DaveWoodCom
Copy link

Line 136:

if (!SecItemCopyMatching((__bridge CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) == noErr)

can be changed to

if (SecItemCopyMatching((__bridge CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) != noErr)

to prevent a warning in Xcode 7.3.

This just moves the ! over and compares != noErr instead of inverting the Int and doing the comparison.

@chrisridd
Copy link

chrisridd commented May 17, 2016

I'm hitting a problem in the iOS 9.3 simulator in Xcode 7.3.1. I create and update a single item in the keychain with a username and password. I'm not using access groups (it is nil in the initWithIdentifier:accessGroup: method). I have not tried my code out on a real device since discovering this problem.

However when I stop and rerun the app in the simulator, I do a sanity check search after [super init] in the initWithIdentifier:accessGroup: method:

    NSMutableDictionary *query = [[NSMutableDictionary alloc] init];
    [query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    [query setObject:(__bridge id)kSecMatchLimitAll forKey:(__bridge id)kSecMatchLimit];
    [query setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnAttributes];
    err = SecItemCopyMatching((__bridge CFDictionaryRef)query, (CFTypeRef *)&results);

This helped during development to detect any "crud" entered in the keychain - I then use SecItemDelete() to delete each one.

However the query now returns two items matching what we've created:

<__NSCFArray 0x7fc4e8f11660>(
{
    acct = "my.user.name";
    agrp = test;
    cdat = "2016-05-17 13:51:15 +0000";
    desc = "";
    gena = Password;
    labl = "";
    mdat = "2016-05-17 13:51:19 +0000";
    musr = <>;
    pdmn = ak;
    svce = "";
    sync = 0;
    tomb = 0;
},
{
    acct = "engine-state";
    agrp = "com.apple.security.sos";
    cdat = "2016-05-17 13:51:19 +0000";
    mdat = "2016-05-17 13:51:19 +0000";
    musr = <>;
    pdmn = dk;
    svce = "SOSDataSource-ak";
    sync = 0;
    tomb = 0;
}
)

What's the engine-state in the result? Why is the access group called "test"? Should I be using access groups explicitly now, even in the simulator?

@johndpope-karhoo
Copy link

johndpope-karhoo commented Sep 12, 2016

Xcode 8 - GM - simulator crash
screen shot 2016-09-12 at 15 10 48

@johndpope-karhoo
Copy link

fyi - a reworked version https://gist.github.com/kristopherjohnson/5212625

That error I was getting is related to 34018 / entitlements missing. By turning on keychain sharing it does work.
Someone else has a solution by code in this ticket. I wasn't able to merge logic into this though.
http://stackoverflow.com/questions/29740952/osstatus-error-code-34018

@mnang
Copy link

mnang commented Sep 20, 2016

I'm getting the *** Assertion failure in -[KeychainItemWrapper resetKeychainItem] error in Xcode 8.0.
Here is the code in my App:

  • (void)resetKeychainItem
    {
    OSStatus junk = noErr;
    if (!keychainItemData)
    {
    self.keychainItemData = [[NSMutableDictionary alloc] init];
    }
    else if (keychainItemData)
    {
    NSMutableDictionary *tempDictionary = [self dictionaryToSecItemFormat:keychainItemData];
    junk = SecItemDelete((__bridge CFDictionaryRef)tempDictionary);
    NSAssert( junk == noErr || junk == errSecItemNotFound, @"Problem deleting current dictionary." );
    }

    // Default attributes for keychain item.
    [keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrAccount];
    [keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrLabel];
    [keychainItemData setObject:@"" forKey:(__bridge id)kSecAttrDescription];

    // Default data for keychain item.
    [keychainItemData setObject:@"" forKey:(__bridge id)kSecValueData];
    }

Any help would be appreciated.

@dcolter
Copy link

dcolter commented Dec 19, 2016

Hi David. I realize that this is a copy of 5 year old code & in Objective-C. Still, it took me quite a while to understand how to use it with iCloud syncing. Finding and saving where not effective at all. Are you interested in adding or having comments added showing how to do this? If so, please describe how to make changes to your gist.

Thank you so much for posting this.... I wasn't quite ready for the jump to Swift.

David

@spartacus9
Copy link

Curse these wretched chains for
Scared and afraid are the hounds of hell
When they hear that clank and that rusty bel.
^
|
|
|
This is what working with KeyChain does to people, they start writing out of frustration.

@GabLeRoux
Copy link

GabLeRoux commented Apr 29, 2017

⚠️ I don't recommend using this script.
You probably ended up here by googling something like "ios keychain wrapper". Use this and chances are you'll have troubles accessing keychain in some situations with xcode 8. I think it's better to use one of the cocoapod libs available out there. At least, some of them have tests 🎉.

Have a look here, many solutions for both swift and objective-c are waiting for you:
https://github.com/vsouza/awesome-ios#keychain

@stile1201
Copy link

Remarkable that, in the 7 years since Apple published this, it seems no one has picked up the big in line 136. It's pure luck that this code works at all.

@PawanAhire
Copy link

Hello,
I am getting crash for iOS 11.4.1.
Line: NSAssert(NO, @"Serious error, no matching item found in the keychain.\n");
Crash Report:
CoreFoundation 0x0000000184806d8c __exceptionPreprocess + 224
libobjc.A.dylib 0x00000001839c05ec objc_exception_throw + 52
CoreFoundation 0x0000000184806bf8 +[NSException raise:format:arguments:] + 100
Foundation 0x00000001851f6fa0 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 108
CheckPoint 0x0000000100b468d8 -[KeychainItemWrapper secItemFormatToDictionary:] (KeychainItemWrapper.m:278)
CheckPoint 0x0000000100b45d34 -[KeychainItemWrapper initWithIdentifier:accessGroup:] (KeychainItemWrapper.m:163)

Crash Exception thrown : “NSInternalInconsistencyException: Serious error, no matching item found in the keychain. “

Copy link

ghost commented Sep 5, 2018

Hello,
I am getting crash for iOS 11.4.1.
Line: NSAssert(NO, @"Serious error, no matching item found in the keychain.\n");
Crash Report:
CoreFoundation 0x0000000184806d8c __exceptionPreprocess + 224
libobjc.A.dylib 0x00000001839c05ec objc_exception_throw + 52
CoreFoundation 0x0000000184806bf8 +[NSException raise:format:arguments:] + 100
Foundation 0x00000001851f6fa0 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 108
CheckPoint 0x0000000100b468d8 -[KeychainItemWrapper secItemFormatToDictionary:] (KeychainItemWrapper.m:278)
CheckPoint 0x0000000100b45d34 -[KeychainItemWrapper initWithIdentifier:accessGroup:] (KeychainItemWrapper.m:163)

Crash Exception thrown : “NSInternalInconsistencyException: Serious error, no matching item found in the keychain. “

@247software-sandip-pawar

Any Update about crash?

@247software-sandip-pawar

Hello,
I have found solution for above crash
Setting kSecAttrAccessible such as kSecAttrAccessibleAfterFirstUnlock to the query will allow the keychain to be accessible when the device is locked.

What do you think about fixing this issue? Should we add kSecAttrAccessible property to the query to allow to copy keychain data when the device is locked?

A workaround is to start the listener when the app starts and keeps the listener running when the app is in background.

Thanks,
Sandip Pawar

@samnangcreative
Copy link

I'm SAM new iOS Developer, Anybody can show me how to use KeychainItemWrapper.h and KeychainItemWrapper.m put to xCode project because i'm use WKWebview for user login and after user exit my app and reopen need user login again and again. Please show me example coding

@aliakhtar49
Copy link

Can someone look into this crash happening on release build .

Link

I am using nil access group if this is a reason How can I reproduce it ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment