使用Monotouch在钥匙串中存储和读取密码

Kru*_*lur 7 xamarin.ios

编辑:问题已经解决.为社区做出贡献,我设置了一些帮助方法,并举例说明如何在我的博客上使用它们.在这里找到KeyChain MT示例

- 原始问题:

在模拟器和iPad上运行iOS4.2.

我正在尝试使用下面的代码存储和读取钥匙串中的密码.我对代码的灵感来自https://github.com/ldandersen/scifihifi-iphone/,但我无法让它工作.我错过了什么?

// Create a record.
SecRecord o = new SecRecord ( SecKind.GenericPassword );
o.Service = "myService";
o.Label = "myService";
o.Account = "test@test.com";
// 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 = "test@test.com";

// 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 ) );
Run Code Online (Sandbox Code Playgroud)

Luk*_*uke 5

除了使用SecRecord.ValueData尝试:

Console.WriteLine(NSString.FromData(data.Generic, NSStringEncoding.ASCIIStringEncoding));
Run Code Online (Sandbox Code Playgroud)

GenericSecKind.GenericPassword存储的位置返回NSData .