Search code examples
c#iosxamarinxamarin.ioskeychain

How to correctly use SecRecord (KeyChain)?


So I have some code which I originally took from Xamarin.Auth to store sensitive data on the device such as password:

var record = new SecRecord(SecKind.GenericPassword);
record.Service =  "MyServiceId"
record.Generic = NSData.FromString(value, NSStringEncoding.UTF8); ;
record.Accessible = SecAccessible.WhenUnlocked;

statusCode = SecKeyChain.Add(record);

and my guess is that the data stored is encrypted with SecKind.GenericPassword. But how is this password being generated and where is this value then being stored. The Xamarin documentation is very sparse ans just says:

The SecRecord stores a password.

Who may have access to the value I store, is this the correct way to use the KeyStore?


Solution

  • In order to limit how this record is accessed you can use the AccessControl property when you create it instead of just Accessible:

    record.AccessControl = new SecAccessControl(
        SecAccessible.WhenUnlocked,
        SecAccessControlCreateFlags.UserPresence);
    

    See: https://developer.xamarin.com/api/type/Security.SecAccessControlCreateFlags/ for more Flags you can apply.

    SecKind is just the type of record you are storing. Who creates the password doesn't matter, it could be your App, it could be something you get from an API or whatever.

    You can also refer to the official Apple documentation: https://developer.apple.com/documentation/security/keychain_services/keychain_items