Friday, September 11, 2015

Simple Xamarin iOS Keychain code

I had searched and found a few decent examples of KeyChain (iOS) usage in Xamarin

I had searched and found a few decent examples of KeyChain (iOS) usage in Xamarin but not exactly the code I was happy with.

So this is more of a mashup of pieces of the good code I found formed into one utility class.

The key essentials are find an existing key, create a new key, delete a previous key. The examples I saw tried to do all of this in one method, it's better to break things up, have one method per responsilibity.

using Security;
using Foundation;

public class KeyChain
{

    public string ValueForKey(string key)
    {
        var record = ExistingRecordForKey (key);
        SecStatusCode resultCode;
        var match = SecKeyChain.QueryAsRecord(record, out resultCode);

        if (resultCode == SecStatusCode.Success)
            return NSString.FromData (match.ValueData, NSStringEncoding.UTF8);
        else
            return String.Empty;
    }

    public void SetValueForKey(string value, string key) 
    {
        var record = ExistingRecordForKey (key);            
        if (value.IsNullOrEmpty())
        {
            if (!ValueForKey(key).IsNullOrEmpty())
                RemoveRecord(record);

            return;
        }

        // if the key already exists, remove it
        if (!ValueForKey(key).IsNullOrEmpty())
            RemoveRecord(record);

        var result = SecKeyChain.Add(CreateRecordForNewKeyValue(key, value));
        if (result != SecStatusCode.Success)
        {
            throw new Exception(String.Format("Error adding record: {0}", result));
        }
    }

    private SecRecord CreateRecordForNewKeyValue(string key, string value)
    {
        return new SecRecord(SecKind.GenericPassword)
        {
            Account = key,
            Service = ServiceName,
            Label = key,
            ValueData = NSData.FromString(value, NSStringEncoding.UTF8),
        };
    }

    private SecRecord ExistingRecordForKey(string key)
    {
        return new SecRecord(SecKind.GenericPassword)
        {
            Account = key,
            Service = ServiceName,
            Label = key,
        };
    }

    private bool RemoveRecord(SecRecord record)
    {
        var result = SecKeyChain.Remove(record);
        if (result != SecStatusCode.Success)
        {
            throw new Exception(String.Format("Error removing record: {0}", result));
        }

        return true;
    }        
}

23 comments:

  1. Thank you so much Mark! I just spent the last three hours looking for something this simple. Most examples I had found seemed overly complicated and not generic enough to handle simple key/value data. I can't believe there aren't more examples of using Keychain for Xamarin iOS out there, anyways thank you!

    ReplyDelete
  2. Can You Provide Example of "How to share Keychain between iOS apps in XAMARIN"
    Reference:
    http://stackoverflow.com/questions/4115744/how-to-share-keychain-data-between-ios-applications
    http://evgenii.com/blog/sharing-keychain-in-ios/

    ReplyDelete
  3. what is ServiceName in your code? thanks!

    ReplyDelete
    Replies
    1. Actually not sure, I believe it's an extra value I forgot to take out of the code, there is a Service property on the SecRecord and you can set it to whatever you like. So you could pass in another string into the method (key, value, serviceName). I believe the purpose of Service separates the sets of key values into groups by Service.

      Delete
  4. Hi mark.
    Your explanation is great. However i'm trying to do something similar but with a bit difference.
    Could you please read my thread here

    https://stackoverflow.com/questions/49381392/c-sharp-how-to-store-rsa-key-pair-on-ios-keychain-xamarin

    and if possible give me some tips please?
    Many thanks in advance

    ReplyDelete
  5. This is my first visit to your web journal! We are a group of volunteers and new activities in the same specialty. Website gave us helpful data to work. https://foodkeychains.com/

    ReplyDelete
  6. On the off chance that you have your go to put for repair parts for iPhone 3g handsets previously set to go, it will involve basically squeezing the catch and pausing. Handy reparatur

    ReplyDelete
  7. The world needs no presentation in regards to the contention among iOS and Android advanced cells. While the applications and offices gave by both Android and iOS working frameworks is a great deal not quite the same as one another, yet the world advanced mobile phone client base gets tremendously influenced with each new dispatch from these mammoths. myjio app

    ReplyDelete
  8. Positive site, where did u come up with the information on this posting? I'm pleased I discovered it though, ill be checking back soon to find out what additional posts you include. Iosem

    ReplyDelete
  9. We offer a comprehensive plumbing service, to deal with all those unpleasant emergencies or small plumbing tasks that you simply don’t want to handle yourself.  basicknowledgehub

    ReplyDelete
  10. This post is really helpful to know. Thank you very much motorcycle key chain

    ReplyDelete
  11. this is my first website for comment because i realy like this website as best ufc

    ReplyDelete
  12. The latest version of Zenonia 3 Apk has been released and this time, it's an RPG. Available for free on Android and iOS, it comes with a lot of improvements, such as the new ending system and smoother gameplay.

    ReplyDelete
  13. GBwhatsapp apk download is a new android application. The intention of this app is to be an alternative to other messaging applications like whatsapp. This app basically allows user to communicate freely with each other through instant messaging, voice calls and video calls. Our gbwhatsapp apk gives you unlimited features.

    ReplyDelete
  14. Roblox is a game that is available on android, ios, and windows. It allows you to create your own games as well as play the other games that various players make. One of the unique features of Roblox is how you get robux, you will need to Install Roblox Mod Apk and download free robux hack.

    ReplyDelete
  15. Looking for a game that is worth your time and money? Then Cars Fast as Lightning Mod Apk is the one for you. This is the game where you can select from many different cars and race with other people. Moreover, this game is free. For more Info visit us at https://apknames.com/cars-fast-as-lightning-mod-apk/

    ReplyDelete
  16. How do I make money from making a sport with no
    This หารายได้เสริม is a quick and simple way to make money online betting. No matter how much money you make, it is still possible to win big! How to Make Money Online · Choose the

    ReplyDelete
  17. GTA Vice City OBB is a classic example of a video game that has aged very well. The game was released in 2002 and still looks and plays great. The graphics are astounding for its time and the gameplay is very addictive. The story line is also compelling, making you want to keep playing to find out what happens next.

    ReplyDelete
  18. Humidifier for large rooms is ever best choice for every house. Some areas have issue of low humidity. But you can easily solve this problem with he help of humidifier. Must visit this site.

    ReplyDelete
  19. Forstborn Mod Apk
    This post is really helpful to know. Thank you very much

    ReplyDelete

Mvvm on Mobile?

Here's my talk from Houston Tech Fest 2017. Recorded Talk: Slides: https://speakerdeck.com/markawil/mvvm-and-mobile-dont-do-it...