Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and read password to/from keychain using Monotouch

Tags:

xamarin.ios

EDIT: Issue has been resolved. To contribute a bit to the community I setup some helper methods and an example how to use them on my blog. Find it here KeyChain MT example

-- Original question:

Running iOS4.2 on Simulator and iPad.

I'm trying to store and read a password from the keychain using the code below. My inspiration for the code was https://github.com/ldandersen/scifihifi-iphone/ but I can't get it to work. What am I missing?

// Create a record.
SecRecord o = new SecRecord ( SecKind.GenericPassword );
o.Service = "myService";
o.Label = "myService";
o.Account = "[email protected]";
// The super secret password.
o.Generic = NSData.FromString ( "secret!", NSStringEncoding.UTF8 );
// Add to keychain.
SecKeyChain.Add ( o );

// Now cerate another recored to query what we just saved.  
o = new SecRecord ( SecKind.GenericPassword );
o.Service = "myService";
o.Account = "[email protected]";

// Query as record.         
SecStatusCode code;
var data = SecKeyChain.QueryAsRecord ( o, out code );

// This will tell us "all good!"... 
Console.WriteLine ( code );

// But data.Generic is NULL and this line will crash. :-(
Console.WriteLine ( NSString.FromData ( data.Generic, NSStringEncoding.UTF8 ) );
like image 551
Krumelur Avatar asked Jan 31 '11 14:01

Krumelur


1 Answers

Rather than use SecRecord's .ValueData try this:

Console.WriteLine(NSString.FromData(data.Generic, NSStringEncoding.ASCIIStringEncoding));

Generic returns NSData from where SecKind.GenericPassword's are stored.

like image 97
Luke Avatar answered Oct 14 '22 04:10

Luke