简体   繁体   English

在Apple钥匙串中存储和读取密码的简单方法?

[英]Simple way to store and read a password in apple keychain?

I want a simple way to store and read a password in apple keychain using swift5 for iOS 我想要一种简单的方法来使用iOS的swift5在Apple钥匙串中存储和读取密码

Apple documentation about keychain is a little confusing https://developer.apple.com/documentation/security/keychain_services/keychain_items/adding_a_password_to_the_keychain?language=swift Apple有关钥匙串的文档有些混乱https://developer.apple.com/documentation/security/keychain_services/keychain_items/adding_a_password_to_the_keychain?language=swift

struct Credentials {
    var username: String
    var password: String
}
enum KeychainError: Error {
    case noPassword
    case unexpectedPasswordData
    case unhandledError(status: OSStatus)
}
struct Credentials {
        var username: String
        var password: String
    }

private func storeKeychain(username: String, password: String)throws->Any? {
        let credentials = Credentials.init(username: username, password: password)
        let query: [String: Any] = [kSecClass as String:  kSecClassGenericPassword,
                                    kSecValueData as String: credentials.password]

        let status = SecItemAdd(query as CFDictionary, nil)
        guard status == errSecSuccess else {
            throw KeychainError.unhandledError(status: status) }

        return status
    }

private func getKeychain()throws ->String {
        let query: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
                                    kSecMatchLimit as String: kSecMatchLimitOne,
                                    kSecReturnAttributes as String: true,
                                    kSecReturnData as String: true]
        var item: CFTypeRef?
        let status = SecItemCopyMatching(query as CFDictionary, &item)
        guard status != errSecItemNotFound else { throw KeychainError.noPassword }
        guard status == errSecSuccess else { throw KeychainError.unhandledError(status: status) }

        guard let existingItem = item as? [String : Any],
            let passwordData = existingItem[kSecValueData as String] as? Data,
            let password = String(data: passwordData, encoding: String.Encoding.utf8),
            let account = existingItem[kSecAttrAccount as String] as? String
            else {
                throw KeychainError.unexpectedPasswordData
        }
        _ = Credentials(username: account, password: password)
        return password
    }

override func viewDidLoad() {
        super.viewDidLoad()
           let keychains = try? storeKeychain(username: "John", password: "12345678")
        let password = try? getKeychain()
        print(password)
}

Should print 12345678 but prints Optional("f9dd6069-4e51-4c18-9dc6-7db6254271e3") 应该打印12345678,但打印Optional(“ f9dd6069-4e51-4c18-9dc6-7db6254271e3”)

You are storing password as a string inside keychain. 您正在将密码作为字符串存储在钥匙串中。 I will modify storeKeychain() method 我将修改storeKeychain()方法

private func storeKeychain(username: String, password: String) throws -> Any? {
    let credentials = Credentials.init(username: username, password: password)
    let data = credentials.password.data(using: .utf8)!

// store password as data and if you want to store username
    let query: [String: Any] = [kSecClass as String:  kSecClassGenericPassword,
                                kSecAttrAccount as String: username,
                                kSecValueData as String: data]
    let status = SecItemAdd(query as CFDictionary, nil)
    guard status == errSecSuccess else {
        throw KeychainError.unhandledError(status: status) }
    return status
}

Check if it works. 检查是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Apple钥匙串丢失用户名/密码信息 - Apple Keychain losing Username / password information 为什么要在iPhone应用程序的钥匙串中存储用户名和密码 - Why to store username and password in Keychain in iPhone app 如何在iPad的钥匙串实用程序中存储密码 - How store password in keychain utilities in iPad IOS在钥匙串中存储多个密码 - IOS store more than one password in keychain 我应该使用苹果登录将用户标识符存储在钥匙串中吗? - Shoud I store user-identifier in keychain using sign in with apple? 我应该用哪个密钥在iOS钥匙串中存储密码? - which key should I use to store the password in iOS keychain? 在钥匙串中存储用于加密密码的密钥的最佳位置在哪里? - Where is the best place to store the key for encryption a password in keychain? Apple App Store:是否允许使用密码保护的应用程序? - Apple App Store: Are password protected apps allowed? 当应用程序被沙盒化时,为什么 Apple 建议将密码、机密和密钥存储在 iOS Keychain 中? - Why does Apple recommend to store passwords, secrets, and keys in iOS Keychain when apps are sandboxed? 获取Apple Keychain以识别Bouncy Castle .NET创建的PKCS12(.p12)商店 - Get Apple Keychain to recognize Bouncy Castle .NET created PKCS12 (.p12) store
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM