So you’re working with Unity3D and building the next big hit game for iOS devices. Ain’t we all. You’ll also need to store user credentials, like unique identifier and password that the player uses to access your servers for the latest content, leaderboards and whatnot. First, you might think that Unity’s own PlayerPrefs is the way to go and many have done so, but there is a problem. A big problem.

PlayerPrefs is not secure. In fact on iOS, it’s just a wrapper for NSUserDefaults, so it’s no more secure than that. There are ways to make them more secure by using encryption and there are lots of resources for that as well, but why not delve a bit deeper into the world of iOS and discover this thing called KeyChain.

Enter the KeyChain

On Apple’s own documentation, they say: “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.”

Great! This is just what we want! But how do we access it from Unity? I spent days looking for a ready-made implementation of a plugin that would handle the keychain access for me, but came up with nothing so I decided it was time to roll my own. As an interesting fact, we had been talking about this at work as we needed this type of storage for storing some identifiers that would need to be preserved even if the app is uninstalled. You too, can roll your own plugin for Unity by using open-source implementations like SSKeychain, but why bother when you can head to the Unity Asset Store and grab the plugin I’ve made.

Use cases

To conclude, I’ve come up with a couple of use cases for Keychain in games.

First, you can use Keychain to store your user’s account credentials there in a secure manner for quick login when the app is fired up.

Second, you can use Keychain to store unique identifiers that identify the user and/or her progress inside the game. One of the features in Keychain services is that the data stored in it persists even if the app has been uninstalled. This has been utilized by a great deal of games, if I’d have to mention one that would be Boom Beach (as I’ve been playing it a lot lately).

Third, use keychain as a secure version of PlayerPrefs and store arbitrary data from the game itself. This is not the intended usage, but works with a bit of trickery. Combine this with your own encryption, and you can wave bye-bye to people hacking your PlayerPrefs for their own gain.

So, head out to http://u3d.as/bVu and grab the plugin. It’ll be worth it.