public
Last active

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.

  • Download Gist
KeychainItemWrapper.h
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
/*
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
KeychainItemWrapper.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
/*
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

I am facing issue with ARC conversion with newer version of XCode 4.2 on following statement.

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

Following statement from your code is not working for me. It give some ARC error for outDictionary.
if (!SecItemCopyMatching((__bridge CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) == noErr)
{......

Please guide me.

Thanks,
Yogesh

Well, that code you are having problems with is NOT in the code I posted here. Not sure where you got it, but the above code I posted compiles and works fine in the latest Xcode 4.2. The problem with your line is the "objc_unretainedPointer" function which as I understand it is not public.

Thanks David, for your pointer. This key chain wrapper i converted for ARC by myself. But in latest version of XCode 4.2 it was crashing.

Your code is working fine.

Difference as bellow-
In my code
NSMutableDictionary *outDictionary = nil;
In your code
CFMutableDictionaryRef outDictionary = NULL;

Now my code is also working fine.

__bridge internally using objc_unretainedPointer so why we can't directly use it. Do you know any link where i can get public and private API reference.

Any ways thanks a lot..... :)

Hey David,
I have an issue with your ARCified Keychain Wrapper (great work, by the way).

When I try to add something to the Keychain like this:

KeychainItemWrapper *wrapper = [[KeychainItemWrapper alloc]initWithIdentifier:keyChainIdentifier accessGroup:nil];
[wrapper setObject:self.password forKey:@"password"];

I get a the following error
Assertion failure in -[KeychainItemWrapper writeToKeychain], .../.../KeychainItemWrapper.Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Couldn't add the Keychain Item.m:309

As you see I don't use an accessgroup so there shouldn't be any issues with the entitlements.plist
Do you have any idea what the problem could be?

Thanks in advance.
Benny

I really don't know. After I posted the code I modified it to take a
dictionary instead of a string.

David

Hi,

I found a "solution" just a few minutes ago.
When I use "(__bridge id)kSecValueData" as the key in [wrapper setObject:... forKey:..] it works though I don't understand it.

But thanks for that quick reply!

Shouldn't
#if __has_feature(objc_arc)
#error THIS CODE MUST BE COMPILED WITH ARC ENABLED!
#endif
be checking if arc ISN'T enabled?

Hi David, I'm getting an EXC_BAD_ACCESS at line 244 in the .m:

if (SecItemCopyMatching((__bridge CFDictionaryRef)returnDictionary, (CFTypeRef *)&passwordData) == noErr)

Any ideas?

Add a NSLog message just before that function call and log both dictionaryToConvert and also returnDictionary. See if they are what you think they should be. This exact code has been working flawlessly for me with ARC for close to 6 months now.

Thanks, to be honest I'm very new to iOS development so it's almost certainly a problem with my code.

This is my first time using keychain in any scenario so I wonder if you could point me in the direction of some simple sample code that puts/gets to/from the keychain?

Apple has some sample code - I thought this piece was taken from it. This is not the easiest API to use. I'm 100% sure you can find something if you google around, look on Apple's developer site (at the sample code). I just don't have time right now to go look myself.

IMHO if you can use in line 250

NSString *password = [[NSString alloc] initWithData:(__bridge_transfer NSData *)passwordData encoding:NSUTF8StringEncoding];

and as a result of using "__bridge_transfer" you don't need the release in 259.

What happens then on the "else" - the enclosing if() statement fails? That is why I did it that way.

well the expectation is

if ( SecItemCopyMatching( ..., (CFTypeRef *)&passwordData ) == noErr) {
// passwordData has a value and therefore you can transfer the ownership to ARC
} else {
// passwordData stay NULL and therefore nothing to release
}

Do you know a conditions where you get passwordData and the return value is not noErr?
But to avoid this risk you can move the release statement in line 259 in the else part

Hi, great work! While debugging I found something that I can't explain though:

When I do NSLog(@"account = %@", [keyChain objectForKey:(__bridge id)kSecAttrAccount]); the password gets printed.

But when I pass exactly the same reference to a textfield (i.e. _userNameTextField.text = ...) it displays the user name.

You know what ... I'm an idiot, I switched the symbol names on the username and password field :(

Thank you for providing this source code to others.

It was very kind of you to just post a thank you - trust me, its quite rare! Good luck with it!

Thanks for this. Wouldn't it be possible to use Apple's non-ARC code and just turn off ARC for the Apple files?

Well, that is probably true, however someone would need to rigorously analyze the code to verify it doesn't break any of the heuristics that ARC brings into play, like all objects from init are retained, all objects from factory nondescript methods are autoreleased, etc.

This way you know you have no memory leaks since clang would notify you. You cannot assume that all Apple sample code is perfect. I prefer having it vetted by a good complier!

I did three things to use Apple's current sample code in my ARC projects:

1) Set -fno-objc-arc as a compiler flag on KeychainItemWrapper.m under Build Phases, Compile Sources.
2) Use __bridge_transfer in the call to the wrapper: NSString *password = [wrapper objectForKey:(__bridge_transfer id)kSecValueData];
3) Add an autorelease to line 196 of Apple's code to plug Apple's memory leak: self.keychainItemData = [[[NSMutableDictionary alloc] init] autorelease];

Works and is vetted by the compiler. ;)

Well, not sure why you even visited this gist. I never claimed you HAD to do this - just that if you wanted ARC compliant code you could take it. I converted every piece of code used in my companies app to ARC on general principal. Apple clearly says you do not have to do this, as you can use the flag above. Others have had the same desire as me and have been glad to have found this code.

Hello
Thank you for providing this for ARC. I am using this to try and store info in the keychain.
I have used [keychainItem setObject:PassWordInput.text forKey:(__bridge id)(kSecValueData)]; but if I wanna store more than 1 value which needs to be encrypted, how would I go about doing that?

Can you somehow add an identifier, since from what I understand the kSecValueData means the value should be encrypted?

Thanks

Hi,

I am not able to get the stored key chain data .please show me how to retrieve the data from key chain for item.Thanks in advance

Thanks for providing this. FWIW, I've made my own version that modernizes the code a bit, using dictionary subscript notation and default synthesized members. It doesn't do anything your version doesn't do, but I find it easier to understand.

https://gist.github.com/kristopherjohnson/5212625

@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.

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];

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.