Thursday, May 26, 2016

Storing more entries in Keychain

Recently i got a requirement that involves storing more than one entry in the keychain.Apparently keychain accepts one entry for the application.

We know keychain in iOS are unique to each application.And we store as "Key-value" combination in keychain.Both keys and values can be strings.Now the problem is what if there is a need to store more than one entry in keychain for the same application.

Solution is Create a mutable dictionary and add "key-value" entries in the same dictionary each for entry you wanted to save in keychain.

For instance:

I want to save username,password,last login time in the keychain.Then create a dictionary called "User details" and going to add "username":"xyz" ,"Password":"1234","Last login time":"12:34:45pm"

Our dictionary "User details" looks like
username   xyz
password 1234
last login time 12:34:45

Then add this entire "User details" dictionary in keychain like below:

Code excerpts are in Xamarin.But it gives you idea fairly about

//entry in dictionary
            keyItemsDict.SetValueForKey (NSObject.FromObject(value),(NSString)key);
            keyItemsDict.SetValueForKey (NSObject.FromObject(Convert.ToBase64String(value)),keyStr);

            NSData dicDt = NSJsonSerialization.Serialize (keyItemsDict,0,out error);
//keyItemsDict is a dictionary            var s = new SecRecord (SecKind.GenericPassword) {
                ValueData =dicDt,
                Generic = NSData.FromString ("KeyChain")
            };

            SecKeyChain.Add (s);  //add in keychain

No comments:

Post a Comment