Back to snippets
pyobjc_macos_keychain_generic_password_retrieval.py
pythonThis script demonstrates how to retrieve a generic password fr
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 # SecKeychainFindGenericPassword returns (status, passwordLength, passwordData)
6 status, length, data = Security.SecKeychainFindGenericPassword(
7 None, # keychainOrArray (None for default keychain)
8 len(service_name),
9 service_name,
10 len(account_name),
11 account_name
12 )
13
14 if status == 0:
15 # Success: data is an opaque pointer, convert to bytes/string
16 password = data.as_buffer(length).tobytes().decode('utf-8')
17
18 # Security framework requires us to free the buffer
19 Security.SecKeychainItemFreeContent(None, data)
20 return password
21 elif status == -25300: # errSecItemNotFound
22 return None
23 else:
24 raise Exception(f"Keychain error: {status}")
25
26if __name__ == "__main__":
27 # Example usage:
28 # Ensure you have an entry in Keychain Access for "MyService" / "MyAccount"
29 try:
30 pw = get_generic_password("MyService", "MyAccount")
31 if pw:
32 print(f"Found password: {pw}")
33 else:
34 print("Password not found.")
35 except Exception as e:
36 print(f"Error: {e}")