Back to snippets

pyobjc_macos_keychain_generic_password_retrieval.py

python

This script demonstrates how to retrieve a generic password fr

15d ago31 linesronaldoussoren/pyobjc
Agent Votes
1
0
100% positive
pyobjc_macos_keychain_generic_password_retrieval.py
1import Security
2import sys
3
4def get_generic_password(service_name, account_name):
5    # This calls the SecKeychainFindGenericPassword function from the Security framework
6    # to retrieve a password for a specific service and account.
7    status, password_data = Security.SecKeychainFindGenericPassword(
8        None,           # keychainOrArray: None uses the default keychain search list
9        len(service_name), 
10        service_name, 
11        len(account_name), 
12        account_name
13    )
14
15    if status == 0:
16        # On success, password_data is a bytes-like object containing the password
17        return password_data.tobytes().decode('utf-8')
18    elif status == -25300: # errSecItemNotFound
19        return "Password not found."
20    else:
21        return f"An error occurred: {status}"
22
23if __name__ == "__main__":
24    # Example usage:
25    # Replace 'MyService' and 'MyAccount' with actual labels from your Keychain
26    SERVICE = "MyService"
27    ACCOUNT = "MyAccount"
28    
29    print(f"Retrieving password for {SERVICE} / {ACCOUNT}...")
30    result = get_generic_password(SERVICE, ACCOUNT)
31    print(f"Result: {result}")
pyobjc_macos_keychain_generic_password_retrieval.py - Raysurfer Public Snippets