5

我正在尝试保存这样的记录:

var testRecord = new SecRecord(SecKind.GenericPassword)
{
    CreationDate = DateTime.UtcNow,
    MatchCaseInsensitive = false,
    Service = "MyService",
    Label = "MyService",
    Account = "User",
    Generic = NSData.FromString("test", NSStringEncoding.UTF8),
};
SecKeyChain.Add(testRecord);

...但是当我在模拟器中运行它时,我得到了 SecStatusCode.Param。根据文档,该代码表示​​“传递的参数无效或不完整”,但我没有看到其他人没有明显成功的任何缺失或异常。

即使将 CreationDate、Invisible、Description、Comment、AccessibleValueData 属性添加到 SecRecord(某些如本示例中)也无济于事 - 仍然获得 SecStatusCode.Param。

是否有任何不明显的事情可能导致返回 Param 状态代码?

4

2 回答 2

11

我在尝试使用钥匙串时遇到了很多麻烦。我终于开始在应用程序中存储用户凭据。这是我所拥有的:

        SecRecord existingRec = new SecRecord (SecKind.GenericPassword) { 
            Service = Keychain.USER_SERVICE, 
            Label = Keychain.USER_LABEL 
        };

        var record = new SecRecord (SecKind.GenericPassword) {
            Service = Keychain.USER_SERVICE, 
            Label = Keychain.USER_LABEL, 
            Account = username,
            ValueData = NSData.FromString (password),
            Accessible = SecAccessible.Always
        };

        SecStatusCode code = SecKeyChain.Add (record);
        if (code == SecStatusCode.DuplicateItem) {
            code = SecKeyChain.Remove (existingRec);
            if (code == SecStatusCode.Success)
                code = SecKeyChain.Add (record);
        }

Keychain 是一个带有常量的静态类,所以我不必重新输入字符串。

你和我唯一不同的是CreationDate/MatchCaseInsensitive属性和 NSData 的编码。也许在没有这些的情况下尝试一下,看看它是否有效?如果是这样,请将它们分别添加回来,看看是什么导致了问题。

于 2012-12-12T18:09:48.853 回答
0

这可能是因为您在模拟器上运行 - 在这种情况下,您需要在当前构建配置的项目选项中添加一个 Entitlements plist 以使钥匙串访问工作。

于 2018-05-11T15:10:12.097 回答