How to get persistent reference to a keychain item in iOS

Keychain is a very good idea from Apple. It lets app developers to store and retrieve sensitive data securely.

Keychain Services provides secure storage of passwords, keys, certificates, and notes for one or more users. A user can unlock a keychain with a single password, and any Keychain Services–aware application can then use that keychain to store and retrieve passwords. Keychain Services Programming Guide contains an overview of Keychain Services, discusses the functions and data structures that are most commonly used by developers, and provides examples of how to use Keychain Services in your own applications.

The following shows how keychain works:

unlocking_keychain. Photo taken from: developer.apple.com

During the process of creating VPN profiles programmatically in iOS 8, the NEVPNProtocol.passwordReference property requires a persistence reference to a keychain item with the kSecClassGenericPassword class. This post covers saving and getting persistence references to a keychain item in iOS.

Getting started with Keychain

The process of saving data in keychain is very simple once you understand it. To start working with Keychain, Security.framework needs to added to your project. Security framework has 4 major methods which enables you to access iOS keychain. These methods are:

  • SecItemAdd
  • SecItemCopyMatching
  • SecItemDelete
  • SecItemUpdate

As it can be guessed from each method’s name SecItemAdd, SecItemDelete and SecItemUpdate adds, deletes and updates data. SecItemCopyMatching method searches for a specific keychain item and copies item data to a reference variable if available. For more information about these four methods checkout Apple’s Keychain Services Reference page.

Saving data

Note: There’s actually no difference in saving normal and persistent references to the keychain!
The following adds a NSData object to the iOS keychain:

NSData *data = [Your data]; // Data to save. It can be a string too.
NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [@"[Your key name]" dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:service forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:data forKey:(__bridge id)kSecValueData];

OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dict, NULL);
if(errSecSuccess != status) {
    NSLog(@"Unable add item with key =%@ error:%ld",key,status);
}

After the data is saved it can be get anytime from keychain.

Getting Data

Data can be get from keychain using the following code:

NSMutableDictionary * dict = [[NSMutableDictionary alloc] init];
[dict setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
NSData *encodedKey = [@"[Your key name]" dataUsingEncoding:NSUTF8StringEncoding];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrGeneric];
[dict setObject:encodedKey forKey:(__bridge id)kSecAttrAccount];
[dict setObject:service forKey:(__bridge id)kSecAttrService];
[dict setObject:(__bridge id)kSecAttrAccessibleAlwaysThisDeviceOnly forKey:(__bridge id)kSecAttrAccessible];
[dict setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
[dict setObject:(id)kCFBooleanTrue forKey:(__bridge id)kSecReturnPersistentRef]; // The most important part
    
CFTypeRef result = NULL;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)dict,&result);
    
if( status != errSecSuccess) {
    NSLog(@"Unable to fetch item for key %@ with error:%ld",key,status);
    return nil;
}
    
NSData *resultData = (__bridge NSData *)result; //Your data is ready

The most important part of the above code is in line 9 where kSecReturnPersistentRef attribute is set. This attribute tells the keychain to return a persistent reference to the keychain item.

Hope it helps 🙂

Introducing timeago: A jQuery library to update fuzzy timestamps automatically

You may have seen at least one of these timestamps in websites especially social networks:

time1

time3

These timestamps are very important and useful in all websites that time matters. But you may have wondered how to implement such a thing in your own web applications.

There are a couple of ways to do so. The first one is to implement this functionality server side. I’ve implemented a server side C# function to do it; but, there would be a very big issue: As the time goes on, the timestamp won’t update! The whole page needs to be refreshed! You may have use ajax to refresh the time but this method also costs lots of resources. The best place to do such a thing is client and that’s exactly what timeago does!

What is timego?

Timeago is a jQuery plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. “4 minutes ago” or “about 1 day ago”).

Timeago has lots of advantages over server side implementation I’ve mentioned above. Here are some:

  • It is very lightweight (About 8KB when not minified and about 4KB when minified and GZiped)
  • Runs on user’s browser; consequently, it won’t cost any server resources.
  • It can be used alongside caching techniques while it runs on client.
  • The timestamps’ values will update live so there’s no need to refresh the whole page or make ajax requests to update them.
  • It’s free and open-source!

How to use timeago?

Using timeago it very simple. Imagine you have a span element in your web page and you want to update the value of this field using timeago. The very first step is to use jquery.timeago.js file in your page’s head element. You also need jQuery library as well; so, add it too if you haven’t:


After that place your ‘span’ as following:

July 17, 2008

As you may have noticed that we put the real datetime we want to calculate from in the ‘title’ attribute. The final step is to add the following piece of javascript in your page:

$(document).ready(function() {
  $("span.timeago").timeago();
});

You’re done! The javascript code above converts all span elements which has “timeago” class.

How to download timeago

Since timeago is an open-source project, it can be found by its GitHub repository or its official website at: http://timeago.yarp.com/. Don’t forget to check out its website for more examples.

This library was very useful for me. Hope it does the same for you.