Search code examples
iosswift3keychain

Storing credentials in keychain encrypted not only password


I need to store userLogin and userPassword in keychain for my app (containing app and extension that use keychain). Since I was searching a lot for some example how to do this I didn't find suitable example for my needs.

Almost every example treats userLogin as an keychain item attribute (which is not encrypted). I need to store credentials encrypted (userLogin + userPassword). How to store it without using kSecAttrAccount attribute. Do I need to store two items (one for login and one for password)?

I'm not using Keychain wrapper so answers in pure raw Keychain api would be great.

My general goal is to ask user one time about userName & userPassword authenticate it fetch authenticationToken if success and store it in keychain. During next app run I need to fetch this token from keychain but I don't have kSecAttrAccount anymore. I don't want to ask user again for userName to fetch authenticationToken. So I though that I can store both (userName & userPassword) in keychain encrypted or store only authenticationToken but then how to fetch it without account information.


Solution

  • Just use a hard-coded account name, and store both the username and password in the data as a dictionary. The data of a keychain item can be anything you want, so use an NSKeyedArchiver to convert a dictionary to data, or convert it to JSON if that's more convenient. On iOS every app group has its own "virtual" keychain (i.e. different app groups won't interfere with each other, even though they're in the same physical keychain), so you don't have to worry about colliding with anyone. Just use whatever field values are convenient for you. Just because it's labeled "account" doesn't mean you have to put the username in there.