nostr_tools.to_bech32¶
- nostr_tools.to_bech32(prefix, hex_str)[source]¶
Convert a hexadecimal string to Bech32 encoded format.
This function converts hexadecimal data to Bech32 encoding with the specified prefix. Bech32 is commonly used for Nostr keys and identifiers as it provides better error detection and is more user-friendly than raw hex.
Common Nostr prefixes: - ‘npub’: Public key (nostr public key) - ‘nsec’: Private key (nostr secret key) - ‘note’: Event ID - ‘nprofile’: Profile identifier - ‘nevent’: Event identifier
- Parameters:
- Returns:
- The Bech32 encoded string with the specified prefix.
Returns empty string if encoding fails.
- Return type:
Examples
Encode public key:
>>> pubkey_hex = "abc123..." # 64-char hex >>> npub = to_bech32('npub', pubkey_hex) >>> print(npub) npub1...
Encode private key:
>>> privkey_hex = "def456..." # 64-char hex >>> nsec = to_bech32('nsec', privkey_hex) >>> print(nsec) nsec1...
Encode event ID:
>>> event_id = "789ghi..." # 64-char hex >>> note_id = to_bech32('note', event_id) >>> print(note_id) note1...
Convert keys for display:
>>> priv, pub = generate_keypair() >>> nsec = to_bech32('nsec', priv) >>> npub = to_bech32('npub', pub) >>> print(f"Your public key: {npub}") >>> print(f"Your private key (keep secret!): {nsec}")
Share event reference:
>>> event_id = event.id >>> shareable_id = to_bech32('note', event_id) >>> print(f"View event: nostr:{shareable_id}")