Forum Xamarin.iOS

Proper use of SecKeyChain ?

binkman71binkman71 USMember ✭✭

So I am trying to save a user's password in the iOS keychain. Saving it the first time isn't a problem. I set up a new SecRecord:

SecRecord sr = new SecRecord( SecKind.GenericPassword );
sr.Account = userNameString;
sr.ValueData = NSData.FromString( userPasswordString );
SecStatusCode ssc = SecKeyChain.Add( sr );

Then I can retrieve it just as easily:

String str;
SecRecord sr = new SecRecord( SecKind.GenericPassword );
sr.Account = userNameString;
NSData find = SecKeyChain.QueryAsData( sr );
if( find != null )
{
        str = find.ToString();
}

However, if the user changes his password, I can never get the record to update. First, I tried using SecKeyChain.Update, but no matter what it always returned SecStatusCode.Param. So then I thought, why not just remove the current record, and re-add it. Only, I get the same return code on the Remove operation:

SecRecord sr = new SecRecord( SecKind.GenericPassword );
sr.Account = userNameString;
SecStatusCode ssc;
SecRecord find = SecKeyChain.QueryAsRecord( sr, out ssc );
if( ssc == SecStatusCode.Success )
{
        ssc = SecKeyChain.Remove( find );
}

The above sets ssc to SecKeyChain.Param, and doesn't remove the record from the keychain. How do I either 1) Use SecKeyChain.Update to properly update the record (this method is not documented by Xamarin), or 2) Properly remove the record from the key chain?

Thanks in advance...

Posts

  • binkman71binkman71 USMember ✭✭

    I got the remove call to work, only I couldn't use it against the QueryAsRecord result:

    SecRecord sr = new SecRecord( SecKind.GenericPassword );
    sr.Account = userNameString;
    SecStatusCode ssc;
    SecRecord find = SecKeyChain.QueryAsRecord( sr, out ssc );
    if( ssc == SecStatusCode.Success )
    {
        sr = new SecRecord( SecKind.GenericPassword );
        sr.Account = userNameString;
        sr.ValueData = find.ValueData;
        SecKeyChain.Remove( sr );
    }
    

    That works...then I can just re-add the user with the new password....

  • KeithRKeithR USMember

    Hi @binkman71‌,

    To update a record, construct the SecRecord for the update record with SecKind.Identity as the argument, as this creates an empty NSMutableDictionary under the hood.

    Keith

Sign In or Register to comment.