Python API Reference
Overview
The {keychain-core} Python API provides a comprehensive, Pythonic interface for cryptographic identity management. Built as a wrapper around the C API, it offers full functionality with Python-specific features like context managers, property decorators, and exception handling.
This is a complete redesign for version 3.0, offering significant improvements over the 2.x Python interface with full support for composable cryptography, DIDs, verifiable credentials, and consensus transactions.
Quick Start
from keychain import Gateway, SecurityLevel
# Initialize and create gateway
settings = Gateway.init("/path/to/keychain.cfg")
gateway = Gateway(settings)
gateway.on_start()
# Create a persona
persona = gateway.create_persona(
"alice", "personal", SecurityLevel.MEDIUM
)
# Your application logic...
gateway.on_stop()
Gateway.close()
Key Features
-
Pythonic Design - Context managers, properties, and intuitive method names
-
Type Safety - Strong typing with proper inheritance hierarchies
-
Memory Management - Automatic cleanup of C resources
-
Exception Handling - Comprehensive exception hierarchy with detailed error information
-
Full API Coverage - Complete access to all Keychain functionality
API Organization
Core Enumerations
Fundamental constants and enumerations for configuration and operation:
- Constants and Enums
-
Complete reference including SecurityLevel, DataType, SerializationFormat, CharEncoding, ConsensusAlgorithm, DidStatus, KeychainType, Version, and all cryptographic algorithm enumerations
Base Classes
Foundation classes providing common functionality:
- KeychainObject
-
Abstract base with automatic memory management
- SerializableObject
-
Base for serializable objects
Core Data Classes
Essential data structures for cryptographic operations:
- Attestation
-
Digital signatures with rich metadata
- Credential
-
W3C verifiable credentials implementation
- EncryptedData
-
Multi-recipient envelope encryption
- KeyLock
-
Access control for encrypted data
- SerializedData
-
Type-safe data serialization
- TagSet
-
Key-value metadata storage
- Transaction
-
Consensus-based ledger transactions
- VerifiableData
-
Digitally signed data with attestations
Identity Management
Classes for managing cryptographic identities:
- Contact
-
External cryptographic identities
- DID
-
W3C Decentralized Identifiers
- Keychain
-
Collections of cryptographic keys
- KeychainDID
-
Keychain-specific DIDs
- KeychainElement
-
Individual cryptographic key elements
- Persona
-
Local cryptographic identities (extends Contact)
- PersonaDID
-
Persona DIDs combining encryption and signature
Gateway and Operations
Main interface and supporting classes:
- Gateway
-
Primary interface for all operations
- Settings
-
Configuration management
- VerificationResult
-
Cryptographic verification results
Design Patterns
Context Managers
All Keychain objects support Python’s context manager protocol:
with Gateway(settings) as gateway:
gateway.on_start()
with gateway.create_persona("alice", "test", SecurityLevel.MEDIUM) as persona:
# Use persona safely
data = persona.encrypt("secret", [contact])
# Automatic cleanup when exiting blocks
Property-Based Access
Classes use Python properties for intuitive access:
# Access persona properties
print(f"Persona: {persona.name}.{persona.subname}")
print(f"DID: {persona.did}")
print(f"Mature: {persona.is_mature}")
print(f"Auto-renew: {persona.auto_renew}")
# Access credential properties
print(f"Credential ID: {credential.id}")
print(f"Issuer: {credential.issuer}")
print(f"Valid: {credential.is_currently_valid()}")
Method Overloading
Key methods support multiple parameter types:
# Encrypt accepts various data types
encrypted1 = gateway.encrypt(persona, "string data", recipients)
encrypted2 = gateway.encrypt(persona, b"bytes data", recipients)
encrypted3 = gateway.encrypt(persona, SerializedData(42), recipients)
encrypted4 = gateway.encrypt(persona, verifiable_data, recipients)
# Verify works with any verifiable object
results1 = gateway.verify(persona, verifiable_data)
results2 = gateway.verify(persona, credential)
results3 = gateway.verify(persona, transaction)
Basic Usage Example
from keychain import (
Gateway, SecurityLevel, SerializedData, TagSet
)
# Initialize
settings = Gateway.init("keychain.cfg")
gateway = Gateway(settings)
gateway.on_start()
try:
# Create personas
alice = gateway.create_persona("alice", "personal", SecurityLevel.MEDIUM)
bob = gateway.create_persona("bob", "work", SecurityLevel.HIGH)
# Add Bob as Alice's contact
bob_contact = gateway.add_contact(alice, "bob", "work", bob.did)
# Sign and encrypt a message
message = SerializedData("Confidential project update")
signed_data = gateway.sign(alice, message)
encrypted_data = gateway.encrypt(alice,
SerializedData(signed_data.serialize()),
[bob_contact])
# Bob receives and processes the message
decrypted_data = gateway.decrypt(bob, encrypted_data)
original_signed = VerifiableData(decrypted_data.bytes())
# Verify signature
verification_results = gateway.verify(bob, original_signed)
if all(result.is_verified for result in verification_results):
print(f"Verified message: {original_signed.content}")
finally:
gateway.on_stop()
Gateway.close()
Migration from 2.x
Key changes when upgrading from Keychain 2.x:
# 2.x style (deprecated)
# persona.get_uri()
# 3.0 style
persona.did
# 2.x style (deprecated)
# gateway.sign() returned string
# 3.0 style
verifiable_data = gateway.sign(persona, data)
# 2.x style (deprecated)
# gateway.encrypt() returned string
# 3.0 style
encrypted_data = gateway.encrypt(persona, data, recipients)
The 3.0 Python API provides:
-
Composable Operations - Chain signing and encryption operations
-
DID Support - W3C Decentralized Identifier integration
-
Verifiable Credentials - Standards-compliant credential management
-
Multi-Signature Support - Multiple attestations on single objects
-
Enhanced Error Handling - Detailed exception hierarchy
-
Better Type Safety - Strong typing throughout the API
See Also
-
xref:../cpp.adoc[C API Reference] - Native C interface
-
C API Reference - C interface documentation
-
Getting Started - Installation and setup
-
Migration Guide - Upgrading from 2.x
-
{w3c-vc-spec}[W3C Verifiable Credentials Specification] - Standards compliance