Keychain sharing is an easy and secure way to share information between apps on the same device. This is even more useful when you think about sharing information between an app and it’s extensions. In my opinion Keychain is just as easy as using NSUserDefaults but provides a greater level of security.
Although Keychain sharing is easy to use, I found the use of Access Groups or kSecAttrAccessGroup somewhat tricky. There are a few different ways of working with Keychain Groups I thought it might be useful to go through the approach I adopted for others looking to implement Keychain sharing within their own apps.
First you will need to setup Keychain sharing in your app. The below are some great tutorials to get you started.
Next, you will need to try to pass information between apps in your Keychain Group. Here is where I ran into my problem. At first I assumed that you simply set the kSecAttrAccessGroup value to the name of the Keychain Group you want to use. No matter the KeyChain Group value I tried, it always returned a nil.
Why? If you open your app’s entitlement file you can see why. Your keychain access group is a calculated value of your Keychain Group and your $(AppIdentifierPrefix).
This means if you set kSecAttrAccessGroup to your keychain access group of com.bencoding.awesome-group it would always return nil. You would need to add the App ID Prefix (also called Team ID) to your Keychain Group. In our example this would be something like ABC1234DEF.com.bencoding.awesome-group.
Getting your App ID Prefix from the developer portal isn’t the end of the world and the tutorials at the beginning of this article do a good job covering why this is necessary.
What is another “magic” string in your app?
If you are building enterprise apps which are often resigned or just hate using “magic” strings this approach leaves you looking for an alternative.
Another approach is to use the Keychain’s own meta data find the App ID Prefix . All you need to do is create a keychain item and then read the returned kSecAttrAccessGroup value from the meta data. Using the provided kSecAttrAccessGroup value you can parse the App ID Prefix and default Keychain Access Group. Removing (or at least reducing) the need for “magic” strings.
I’ve encapsulated this approach into the KeyChainAccessGroupHelper.swift shown at the end of this post.
This approach makes using Keychain sharing with any of the popular Keychain libraries easier. Below demonstrates how to use KeyChainAccessGroupHelper with the KeychainAccess library.
The below gist shows the implementation details of KeyChainAccessGroupHelper.swift
KeyChainAccessGroupHelper is also used as part of the KeyStorage project.