Simple Objective-C wrapper for the keychain that works on Mac and iOS

STKeychain fails to retrieve password after AppStore Update


  • Our app stores the backend token in the device's keychain (STKeychain, ex SFHFKeychainUtils).
  • Background fetch is disabled.
  • An upgrade was recently released.

We're getting reports of users having to re-sign in. This seems to be an issue during STKeychain token-retrieval (stored password is being retrieved as nil).

Is it there any known bugs in STKeychain (or iOS keychain itself) that would cause this kind of issue?

Thanks in advance, any leads will be very welcome!

Source: (StackOverflow)

KeyChain - what is it?

I'm writing my first app for iOS. In it conceived some protection from repetitive actions of the same user device (few, if apple account. Login "login-password" at the application level as such does not exist, therefore it was necessary to implement a hidden identification. Convenient would it be to generate a random number that would be stored somewhere in the user, and remained unchanged even when reinstalling the app.

Started to read it. Learned about SSKeyChain. But just do not have enough experience to understand your logic... Please explain in accessible language!

My assumptions: (please correct if I'm wrong!)

1) each user single Apple account that is attached all apps to one of the device, and thus the storage on the device. Or is the cloud for one account and multiple devices for this account (which is called keychain)?

2) has a free Access to the library SSKeyChain (via the security framework), which I for your application can write any data with their keys (the password to the app, login, color scheme)... so if you reinstall the app, it could check "are there any settings in KeyChain for me?" and take data from there. Similar to NSUserDefaults/SharedPreferences (ios/android), not receding after reinstalling the app.

3) the Possibility of losing data from KeyChain the user device is only shift Apple account any action by Apple.

So? :)

Source: (StackOverflow)

How to create/end run loop to properly deallocate memory?

In my ARC iOS app I am running a for loop that ends up with a large memory allocation overhead. I want to somehow end my for loop with minimal/no extra memory allocated. In this instance I am using the SSKeychain library which lets me fetch things from a keychain. I usually just use autorelease pools and get my memory removed properly but here I don't know what is wrong because I end up with 70 mb + of memory allocated at the end of the loop. I have been told that I should start/end a run loop to properly deal with this. Thoughts?

for (int i = 0; i < 10000; ++i) {
            @autoreleasepool {
                NSError *  error2 = nil;
                SSKeychainQuery*  query2 = [[SSKeychainQuery alloc] init];
                query2.service = @"Eko";
                query2.account = @"loginPINForAccountID-2";
                query2.password = nil;
                [query2 fetch:&error2];

Source: (StackOverflow)

How to create Unique Identifier and save it to identify user(device)

I want to create unique identifier on iOS 5 and use it for identifying user (user device) every time app is started. I am able to create a unique identifier by following code

 CFStringRef string = CFUUIDCreateString(NULL, theUUID);

But unable to save it on user device so that particular identifier is not deleted even when app is uninstalled. I tried using SSKeychain approach but it gives Apple Mach-o Linker error.

Please let me know the the way I can accomplish the same.

Any help is appreciated.

Source: (StackOverflow)

Why SSKeychain returns different result with the same parameters for different iOS apps

I tried to use SSKeychain to reserve UUID on iOS

and the sample code is below

NSString *retrieveuuid = [SSKeychain passwordForService:@"tempApp" account:@"tempUser"];
if (retrieveuuid == nil) {
    //Generate UUID
    CFUUIDRef cfuud = CFUUIDCreate(kCFAllocatorDefault);
    NSString *uuid = CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, cfuuid));
    //save in keychain
    [SSKeychain setPassword:uuid forService:@"tempApp" account:@"tempUser"];
    return uuid;
} else {
    return retrieveuuid;

My question is that I run the first app and then generate a UUID, and then run the second app which has the same parameters, so that the retrieveduuid should not be null, then why the second App returns a different UUID? I think that will return the same UUID as first app because I have saved the UUID in the keychain in App1 and try to retrieve it by the same parameters in App2.

Thanks for help

Source: (StackOverflow)

Evernote sdk for mac can't write to keychain anymore

I wrote a Mac OSX application using the Evernote Mac OSX SDK. It ran for over a year without issues, but now all of the sudden I can't get my Evernote authentication credentials stored. Every time I log in through the popup in my app I see the following in the logs:

OAuth Step 1 - Time Running is: 0.229743
OAuth Step 3 - Time Running is: 0.392775
Error saving to keychain: Error Domain=com.samsoffes.sskeychain Code=-25299 "The operation couldn’t be completed. (com.samsoffes.sskeychain error -25299.)" -25299

Has anyone got an idea what this might be? As far as I can tell their SDK hasn't changed in nearly 2 years so that can't be it.

Source: (StackOverflow)

SSKeyChain not retrieving accounts

I have two iOS applications (app "A" and app "B"), and I need to offer the user the posibility to access to app "B" with the login data stored in app "A" if the user is already loggued in app "A".

What I've done is to use the SSKeyChain library to store the login data of app "A" in the keychain. Something like this:

[SSKeychain setPassword:password forService:@"appA" account:username error:&error];

And then in App "B" I am retrieving this data in this way:

NSError *error;
NSArray *accounts = [SSKeychain accountsForService:@"appA" error:&error];

if (accounts.count > 0)
 // alert to the user

This is working perfect on the simulator, but this not working on my iPhone.

I already also added this line to my didFinishLaunchingWithOptions method:

[SSKeychain setAccessibilityType:kSecAttrAccessibleAlways];

Am I missing something?

Source: (StackOverflow)

What might be causing SecItemAdd or SecItemCopyMatching to fail?

I'm using this method in order to retrieve a saved value (and using SecItemAdd to add it originally):

+ (NSData *)passwordDataForService:(NSString *)service 
        account:(NSString *)account error:(NSError **)error {

    CFTypeRef result = NULL;    
    NSMutableDictionary *query = [self _queryForService:service account:account];

    [query setObject:(__bridge id)kCFBooleanTrue 
        forKey:(__bridge id)kSecReturnData];
    [query setObject:(__bridge id)kSecMatchLimitOne 
        forKey:(__bridge id)kSecMatchLimit];
    status = SecItemCopyMatching((__bridge CFDictionaryRef)query, &result);

    if (status != noErr && error != NULL) {
        *error = [NSError errorWithDomain:kSSKeychainErrorDomain code:status 
        return nil;

    return (__bridge_transfer NSData *)result;

This code is working fine for most users, but a small percentage of my users (< 1%) are experiencing results indicating that either the read or write here is failing. My code unfortunately swallows any errors (i.e. doesn't log them anywhere when they occur) so I can't tell why it's failing out in the world, and I can't reproduce the problem at all on any of my development devices.

Does anyone know of any security/permissions settings that can be enabled on an iOS device that could cause SecItemAdd or SecItemCopyMatching to fail? I've tried turning on passcode locking, but that seems to have no effect.

Source: (StackOverflow)

SSKeychain: Accounts not stored in iCloud?

I'm using sskeychain ( to store my accounts and passwords in the IOS keychain. I assume, that if I store an account, it should be available on my other device. But it doesn't appear there.

I read my accounts with this code:

NSArray *arr=[SSKeychain accountsForService:@"Login"];
for (NSString *s in arr) {
    NSLog(@"Account: %@",s);

and get this (only shown one entry, the others are similar):

Account: {
acct = "";
agrp = "";
cdat = "2014-05-09 22:55:08 +0000";
mdat = "2014-05-09 22:55:08 +0000";
pdmn = ak;
svce = Login;
sync = 0;
tomb = 0;

But this doesn't appear on the other device. Both devices have IOS 7.1.1. I store the password with this line:

  [SSKeychain setPassword:self.passwortField.text forService:@"Login" account:self.userField.text];

I have switched on keychain sharing in Xcode and have a keychain group "de.gondomir.LocalButler" listed there.

Am I missing something? Must the service name something special?


Source: (StackOverflow)

SSKeychain the authenticity of "AppName" cannot be verified

I've recently implemented SSKeychain in my application, every single time i try to access values from the keychain i get prompted to give permission to access the keychain with the message "the authenticity of "AppName" cannot be verified. Do you want to allow access to this item?

i've chosen "Always Allow" about a gillion times but it still prompts me no matter what. its really annoying and looks incredibly unprofessional. pulling my hair out trying to figure out what im doing wrong or how to fix it. to save a password im using

[SSKeychain setPassword:self.passwordField.stringValue forService:@"AppName" account:self.loginField.stringValue];

and to retrieve it

[SSKeychain passwordForService:@"AppName" account:self.loginField.stringValue];

any thoughts?

Source: (StackOverflow)

Potential Loss of Keychain Access Issue After Application Move Account A To B in iOS

Our iOS app is transfer from Account A to B, Earlier we had used the certificates which was created in Account A and upload a build on iTunes Connect using certificates of Account A.

Now when we uploading app on iTunesconenct for Beta Testing that time we have used the certificates which was created in Account B(Due to Transfer App Account).

So, Now application identifier of the live app is different from the application identifier of the Beta TestFlight Testing App on App Store. And we have got the warning potential loss of keychain access.

Right Now, We are using SSKeychain Wrapper for Store UUID to track user. [SSKeychain setPassword:UUID forService:@"com.example.appname” account:@“appname” error:&error]

If App ID Prefix changed then SSKeychain loss it’s access?

Because We track UUID in database for further use using SSKeychain. My doubt is if APPID Prefix changed then it is also effect the SSKeychain and it is generate new UUID for all devices?

So, How we can solve this issue ? Please let us know about solutions of this issue.

Source: (StackOverflow)

Small percentage of users getting errSecItemNotFound when retrieving data from the Keychain

I have an iOS app that stores an access token in the Keychain. In the last few months, I've noticed that around 2% of the users get an errSecItemNotFound when trying to retrieve the token.

All the relevant StackOverflow threads point to background tasks being the culprit (iOS KeyChain not retrieving values from background) or including invalid params in the query string (Keychain: Item reported as errSecItemNotFound, but receive errSecDuplicateItem on addition).

I'm using kSecAttrAccessibleAfterFirstUnlock so background tasks should be able to access the Keychain just fine.

Moreover, the search query looks like this:

NSMutableDictionary *query = [[NSMutableDictionary alloc] init];
[query setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
[query setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
[query setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[query setObject:service forKey:(__bridge id)kSecAttrService];
[query setObject:key forKey:(__bridge id)kSecAttrGeneric];
[query setObject:key forKey:(__bridge id)kSecAttrAccount];

(Setting kSecAttrGeneric is probably redundant, but it does not affect the outcome of the query anyway)

For the record, I've experienced this bug with both SSKeyChain and UICKeychainStore.

Any hints would be highly appreciated :]

Source: (StackOverflow)

Why does this for loop bleed memory?

I am using ARC for my iOS project and am using a library called SSKeychain to access/save items to the keychain. I expect my app to access keychain items once every 10 seconds or so (to access API security token) at peak load and as such I wanted to test this library to see how it handles when called frequently. I made this loop to simulate an insane amount of calls and noticed that it bleeds a significant amount (~75 mb) of memory when run on an iPhone (not simulator):

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    dispatch_async(dispatch_get_main_queue(), ^{
        NSUInteger beginMemory = available_memory();
        for (int i = 0; i < 10000; ++i) {

                NSError *  error2 = nil;
                SSKeychainQuery*  query2 = [[SSKeychainQuery alloc] init];
                query2.service = @"Eko";
                query2.account = @"loginPINForAccountID-2";
                query2.password = nil;
                [query2 fetch:&error2];
        NSUInteger endMemory = available_memory();

        NSLog(@"Started with %u, ended with %u, used %u", beginMemory, endMemory, endMemory-beginMemory);

    return YES;

static NSUInteger available_memory(void) {
    // Requires #import <mach/mach.h>
    NSUInteger result = 0;
    struct task_basic_info info;
    mach_msg_type_number_t size = sizeof(info);
    if (task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size) == KERN_SUCCESS) {
        result = info.resident_size;
    return result;

I am using SSKeychain which can be found here. This test bleeds about ~75 mb of memory regardless if things are actually stored on the keychain.

Any ideas what is happening? Is my testing methodology flawed?

Source: (StackOverflow)

Tutorial on sskeychain and basic auth for iPad apps?

Where can I find a good detailed tutorial using sskeychain to store and retrieve usernames and passwords and to do basic authentication in a UIWebView? Secondarily, am I on the right track as far as the methods needed to store and use authentication for a web based application? (See explanation below.)

I found a couple tutorials using different methods:

According to recommendations from other SO questions below, sskeychain is recommended for an easier use of the keychain to store authentication parameters.

My plan is to store a username and password locally on the device in the keychain as recommended and connect over a UIWebView using basic auth to my PHP code. Is there a good step by step tutorial for xcode/Obj-C newbies on the topic of user authentication that would be recommended by experienced iOS developers?

The Apple documentation seems less than helpful. It's either pages with simple sales jargon or just head imploding descriptions of methods and parameters without many helpful examples.


I ended up just using NSUserDefaults to store the username and password locally and the AFNetworking library to do the authentication. If these are unwise I'd welcome an answer that supplies guidance on a better method.

Source: (StackOverflow)

Keychain doesn't retain the data after app gets update from iTunes

I have been using SSKeychain open source library for storing the data securely in my iOS app. Yesterday, I face an issue ,SSKeychain wasn't able to retain its data when I updated my app from v1.0 to v2.0 from iTunes.

Code for UUID Generation :

- (NSString *)createNewUUID
    CFStringRef string = CFUUIDCreateString(NULL, theUUID);
    return (__bridge NSString *)string;

Over here, I generated a unique device string and used the keychain to store the same and the app heavily depends on unique string/Device Identifier since from iOS5 to iOS7 there are lots of transformations done by Apple in concerned to Unique Device Identifier, since the methods got deprecated.

Cope snippet for Store & Retrive :

NSString *retrieveuuid = [SSKeychain passwordForService:@"" account:@"AppName"];
if (retrieveuuid == nil) {
    NSString *uuid  = [self createNewUUID];

    //Store the password in Keychain
    NSError *error = nil;
    [SSKeychain setPassword:uuid forService:@"" account:@"AppName" error:&error];

    if ([error code] == SSKeychainErrorNotFound) {
        NSLog(@"ID not found");

So, is this something that keychain won't be able to retain its values/identifier, when the app gets updated from Apple OR am I missing out at some point. Please help out if its possible to store the Identifier permanently in device, irrelevant of Installing, uninstalling ,reset and updating the app.

Alternatively, is there any API, which can provide me the same deviceID/unique string when generated so need to store the Unique String?

Note : App has to support iOS 4.3 and above.

Source: (StackOverflow)