Retrieving Keychain Passwords in Swift for macOS

Learn how to retrieve passwords from the Keychain using Swift for macOS development.

In Swift development for macOS applications, securing sensitive information like passwords is equally important. macOS provides a secure storage mechanism called Keychain, where you can store passwords, keys, tokens, and other sensitive data. This tutorial will guide you through the process of retrieving passwords from the Keychain in Swift for macOS applications.

To work with the Keychain, you need to import the Security framework in your Swift file. Now, let’s create a function that retrieves passwords from the Keychain. Add the following function to your Swift file.

import Foundation
import Security

func getKeychainPassword(service: String) -> String? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: service,
        kSecMatchLimit as String: kSecMatchLimitOne,
        kSecReturnAttributes as String: kCFBooleanTrue as Any,
        kSecReturnData as String: kCFBooleanTrue as Any
    ]
    
    var item: CFTypeRef?
    let status = SecItemCopyMatching(query as CFDictionary, &item)
    
    guard status == errSecSuccess else {
        debugPrint("Error retrieving password: \(status)")
        return nil
    }
    
    guard let existingItem = item as? [String: Any],
          let passwordData = existingItem[kSecValueData as String] as? Data,
          let password = String(data: passwordData, encoding: .utf8) else {
        debugPrint("Failed to decode password")
        return nil
    }
    
    return password
}

This function takes one parameter service: A string representing the service associated with the password.

Retrieving Passwords

Now, you can call the getKeychainPassword function to retrieve a password from the Keychain. For example:

let keychainKey = "the keychain key"

print("Getting '\(keychainKey)' from Keychain.")
print("You'll be asked for machine password by macOS.")

if let keychainValue = getKeychainPassword(service: keychainKey)
{
    print("\(keychainKey): \(keychainValue)")
}
else
{
    print("'\(keychainKey)' not found in Keychain")
}

Replace keychainKey with the appropriate value for your application.

For example, if you want to get the password being used by Google Chrome to encrypt the local setting storage, you can set the content of keychainKey with Chrome Safe Storage.

Conclusion

In this tutorial, you learned how to retrieve passwords from the Keychain in Swift for macOS applications. Remember to handle sensitive information securely and responsibly in your applications. Keychain provides a reliable way to store and retrieve sensitive data, helping you build more secure macOS apps.

You can get the code on GitHub.