nostr_tools.generate_keypair¶
- nostr_tools.generate_keypair()[source]¶
Generate a new cryptographically secure private/public key pair for Nostr.
This function creates a new secp256k1 key pair using cryptographically secure random number generation. The keys are suitable for use with the Nostr protocol and can be used to create and sign events.
- Returns:
- Tuple of (private_key_hex, public_key_hex).
private_key_hex: 64-character lowercase hexadecimal string
public_key_hex: 64-character lowercase hexadecimal string (x-only pubkey)
Both keys are suitable for Nostr protocol use.
- Return type:
Examples
Generate new identity:
>>> private_key, public_key = generate_keypair() >>> len(private_key), len(public_key) (64, 64)
Create and sign an event:
>>> priv, pub = generate_keypair() >>> event_dict = generate_event( ... priv, pub, ... kind=1, ... tags=[], ... content="Hello from my new identity!" ... ) >>> event = Event.from_dict(event_dict)
Convert to bech32 format:
>>> priv, pub = generate_keypair() >>> nsec = to_bech32('nsec', priv) >>> npub = to_bech32('npub', pub) >>> print(f"Public key (npub): {npub}") >>> print(f"Private key (nsec): {nsec}")
Validate generated keypair:
>>> priv, pub = generate_keypair() >>> assert validate_keypair(priv, pub) # Always True for fresh keys
Store securely:
>>> priv, pub = generate_keypair() >>> # IMPORTANT: Store private key securely! >>> # Never share or expose private_key >>> save_to_secure_storage(priv) >>> # Public key can be shared freely >>> publish_public_key(pub)