Keychain持久数据iOS

时间:2016-03-16 08:57:00

标签: ios keychain

我正在使用钥匙串来保存持久数据。 其中2个功能是

func savePassword(password: String, inKeychainItem: NSData?) -> NSData?
func getPasswordWithPersistentReference(persistentReference: NSData) -> String?

我只是想确定,如果我使用savePassword函数并获得一个NSData,我应该在哪里保持这个NSData以保持它下次我运行应用程序时的持久性? userDefault是否是保存此数据的安全场所?

编辑:这些是我正在使用的功能

func savePassword(password: String, inKeychainItem: NSData?) -> NSData? {
        guard let passwordData = password.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) else { return nil }
        var status = errSecSuccess

        if let persistentReference = inKeychainItem {
            // A persistent reference was given, update the corresponding keychain item.
            let query: [NSObject: AnyObject] = [
                kSecValuePersistentRef : persistentReference,
                kSecReturnAttributes : kCFBooleanTrue
            ]
            var result: AnyObject?

            // Get the current attributes for the item.
            status = SecItemCopyMatching(query, &result)

            if let attributes = result as? [NSObject: AnyObject] where status == errSecSuccess {
                // Update the attributes with the new data.
                var updateQuery = [NSObject: AnyObject]()
                updateQuery[kSecClass] = kSecClassGenericPassword
                updateQuery[kSecAttrService] = attributes[kSecAttrService]

                var newAttributes = attributes
                newAttributes[kSecValueData] = passwordData

                status = SecItemUpdate(updateQuery, newAttributes)
                if status == errSecSuccess {
                    return persistentReference
                }
            }
        }

func getPasswordWithPersistentReference(persistentReference: NSData) -> String? {
        var result: String?
        let query: [NSObject: AnyObject] = [
            kSecClass : kSecClassGenericPassword,
            kSecReturnData : kCFBooleanTrue,
            kSecValuePersistentRef : persistentReference
        ]

        var returnValue: AnyObject?
        let status = SecItemCopyMatching(query, &returnValue)

        if let passwordData = returnValue as? NSData where status == errSecSuccess {
            result = NSString(data: passwordData, encoding: NSUTF8StringEncoding) as? String
        }
        return result
    }

Edit2:基本上,我只是想检查一下我是否保存了密码,如果我这样做了,那么我想得到它。为此我需要一个persistentReference。我从保存密码功能中获得了一个。但我应该把它放在哪里?

1 个答案:

答案 0 :(得分:0)

如果您使用函数来安全地存储密码。以明文方式编写关键数据足够安全。因为没有人可以访问您的钥匙串。

In iOS, each application always has access to its own keychain items; the user is never asked to unlock the keychain.

无法访问钥匙串的内容信息。