我正在使用idandersen的scifihifi-iphone代码进行钥匙链和保存密码使用

[SFHFKeychainUtils storeUsername:@"User" andPassword:@"123"
              forServiceName:@"TestService" updateExisting:YES error:&error];

当我从设备中删除应用程序时,密码仍然保留在密钥链中。

当用户从设备中删除应用程序时,我想从密钥链中删除密码。我该怎么做呢?


当前回答

c# Xamarin版本

    const string FIRST_RUN = "hasRunBefore";
    var userDefaults = NSUserDefaults.StandardUserDefaults;
    if (!userDefaults.BoolForKey(FIRST_RUN))
    {
        //TODO: remove keychain items
        userDefaults.SetBool(true, FIRST_RUN);
        userDefaults.Synchronize();
    }

... 并从钥匙链中清除记录(上面的TODO注释)

        var securityRecords = new[] { SecKind.GenericPassword,
                                    SecKind.Certificate,
                                    SecKind.Identity,
                                    SecKind.InternetPassword,
                                    SecKind.Key
                                };
        foreach (var recordKind in securityRecords)
        {
            SecRecord query = new SecRecord(recordKind);
            SecKeyChain.Remove(query);
        }

其他回答

只需添加一个应用程序设置包,并实现一个切换,以重置应用程序重启或基于设置(可通过userDefaults)选择的值的钥匙链

这似乎是iOS 10.3的默认行为,基于人们在测试版#2中看到的行为。我还没有找到任何关于这方面的官方文件,所以如果你有请评论。

当应用程序从设备中删除时,没有执行代码的触发器。对keychain的访问依赖于用于对应用程序进行签名的配置文件。因此,没有其他应用程序能够访问密钥链中的此信息。

当用户从设备中删除应用程序时,它不能帮助您删除密钥链中的密码,但它应该让您感到一些安慰,即密码是不可访问的(只能从重新安装原始应用程序)。

对于寻找Swift 3.0版本@amro答案的用户:

let userDefaults = UserDefaults.standard

if !userDefaults.bool(forKey: "hasRunBefore") {
     // Remove Keychain items here

     // Update the flag indicator
     userDefaults.set(true, forKey: "hasRunBefore")
}

*注意,synchronize()函数已弃用

c# Xamarin版本

    const string FIRST_RUN = "hasRunBefore";
    var userDefaults = NSUserDefaults.StandardUserDefaults;
    if (!userDefaults.BoolForKey(FIRST_RUN))
    {
        //TODO: remove keychain items
        userDefaults.SetBool(true, FIRST_RUN);
        userDefaults.Synchronize();
    }

... 并从钥匙链中清除记录(上面的TODO注释)

        var securityRecords = new[] { SecKind.GenericPassword,
                                    SecKind.Certificate,
                                    SecKind.Identity,
                                    SecKind.InternetPassword,
                                    SecKind.Key
                                };
        foreach (var recordKind in securityRecords)
        {
            SecRecord query = new SecRecord(recordKind);
            SecKeyChain.Remove(query);
        }