2011-01-31 136 views
7

编辑:问题已解决。为了向社区贡献一点,我设置了一些帮助程序方法和一个示例,说明如何在我的博客上使用它们。在此查找KeyChain MT example使用Monotouch存储和读取密码钥匙密码

- 原题:

在模拟器和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 = "[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)); 
+0

好博客文章,非常有用,谢谢! – vlad259 2011-02-02 14:27:01

+0

这仍然是公认的方法吗? – servarevitas3 2012-12-18 15:56:16

回答

5

而不是使用SecRecord.ValueData尝试这个办法:从那里SecKind.GenericPassword

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

Generic回报的NSData的存储。