As a developer, you will eventually hit a point of needing to store a user’s login information for some sort of account. Hey! That’s easy, just store that bad boy in any numerous persistent store locations that are available. BUT, you need to make sure that you don’t end up on one of those horror stories in the news where large companies tell everyone they’ve been hacked, and that the thieves ran off with all of your information because everything was in plain text.
Rule #1 Never store any sensitive data with NSUserDefaults!!
Why you might ask? Even though it is really fast and convenient to store key value pairs here, this information is located in a plist that is not compiled into your app’s binary.
How can someone find this plist then? Easy, all you need to do is download a program call iFunBox, or iExplorer, then plug in your device, and you can start exploring all the apps on your device; such as viewing assets, files in the Documents folder, all the plist files, etc.
For an example, I took a peak at the iOS app Outlook that I have on my device, and in no time I was looking at everything they store in NSUserDefaults. For obvious reasons I’m not going to show the actual file being that it has some of my own personal info in there, but here is how I got to the file in iFunBox by opening the app and navigating to the path Outlook -> Library -> Preferences.
f you wanted to still use NSUserDefaults and be more secure, you could encrypt everything before storing. Or use what Apple has already provided you with…the Keychain!
The actual API and documentation for using the Keychain is not easy, so many people have written their own wrapper classes which can be found on github and such. But why put your app’s security in the hands of someone else? So lets jump into some code, in Swift of course.
Here we have a method called saveLogin, which takes a password, a username, and a service. The service and username make up the unique “key” for this password. The service can be any value you want to specify.
Here we are loading a value from the keychain by passing in the service and username we provided for it, pretty straight forward!
So what makes storing these values into the Keychain so great is that they are persistent, even if you uninstall the app and then reinstall, they will still be in the keychain assuming that the bundle id did not change.