# pip install python-gnupg from gnupg import GPG from datetime import datetime def verify_pgp_key( key_data: str, ) -> tuple[bool, str, list[str]]: """ Extract and verify details about a PGP public key. Args: key_data: ASCII-armored PGP public key data Returns: Tuple containing: - Boolean indicating if the key is valid - Error message (empty string if valid) - List of email addresses associated with the key """ try: # Initialize GPG gpg = GPG() # Import the key import_result = gpg.import_keys(key_data) if not import_result.results: return False, "Failed to import key", [] # Get the imported key details keys = gpg.list_keys() if not keys: return False, "No keys found after import", [] # Get the most recently imported key key = keys[-1] # Extract key details print("Key Details:") print(f"Fingerprint: {key['fingerprint']}") print(f"Key ID: {key['keyid']}") print(f"Creation Date: {datetime.fromtimestamp(float(key['date']))}") if "expires" in key and key["expires"]: print(f"Expiration Date: {datetime.fromtimestamp(float(key['expires']))}") # Check expiration if "expires" in key and key["expires"]: expiry_date = datetime.fromtimestamp(float(key["expires"])) if datetime.now() > expiry_date: return False, "Key has expired", [] # Get email addresses from user IDs email_addresses = [] for uid in key["uids"]: # UIDs typically in format: "Name (Comment) " if "<" in uid and ">" in uid: email = uid[uid.rindex("<") + 1 : uid.rindex(">")] email_addresses.append(email) if not email_addresses: return False, "No email addresses found in key", [] # Check key validity if key.get("trust") == "r": # revoked return False, "Key has been revoked", [] return True, "", list(set(email_addresses)) except Exception as e: return False, f"Error processing PGP key: {e}", [] if __name__ == "__main__": # Example usage with open("public_key.asc", "r") as key_file: key_data = key_file.read() success, error, emails = verify_pgp_key(key_data) print(f"Verification success: {success}") if error: print(f"Error: {error}") if emails: print(f"Email addresses: {emails}")