python-nostr icon indicating copy to clipboard operation
python-nostr copied to clipboard

Is there a way to convert from hex to npub?

Open plebiolira opened this issue 2 years ago • 2 comments

Sorry if it's a noob question. I'm looking for a way to input the hex for an event or profile, and convert it to the npub.

I've looked around the codebase quite a bit but couldn't figure it out.

Has it been implemented to python-nostr?

Thanks so much,

plebiolira avatar May 18 '23 14:05 plebiolira

At least on a PrivateKey object, you can use the bech32() method on the public_key attribute. Here's an example from a newly generated PrivateKey.

from nostr.key import PrivateKey

p = PrivateKey()
print(p.public_key.bech32())

weex avatar May 20 '23 04:05 weex

Thanks. I ended up using the hex_to_bech32 method from the monstr library, which I added to my python-nostr.

@staticmethod def hex_to_bech32(key_str: str, spec, prefix='npub'): as_int = [int(key_str[i:i+2], 16) for i in range(0, len(key_str), 2)] data = bech32.convertbits(as_int, 8, 5) return bech32.bech32_encode(prefix, data, spec)

Here's a link to the source. https://github.com/monty888/monstr/blob/5eb21a437a8a640b38b972a6a4c15df55d3d04f9/monstr/encrypt.py#L82

plebiolira avatar May 20 '23 20:05 plebiolira