jeffthibault / python-nostr

A Python library for Nostr
MIT License
270 stars 88 forks source link

ValueError decoding Type 4 DM: "Invalid padding bytes." #68

Closed f321x closed 1 year ago

f321x commented 1 year ago

When trying to decode a received Type 4 DM from Amethyst or Astral i get a Value Error "Invalid padding bytes." (using Nostr 0.0.2 from pip)

Code i used:

if event_msg.event.kind == 4:
                user_pk = event_msg.event.public_key
                content = PrivateKey().decrypt_message(event_msg.event.content, user_pk)
                print(content)

after receiving a type 4 dm it returns the following error:

Traceback (most recent call last): File "/home/benutzer/PycharmProjects/X/testing.py", line 66, in nostr_dalle() File "/home/benutzer/PycharmProjects/X/testing.py", line 58, in nostr_dalle content = PrivateKey().decrypt_message(event_msg.event.content, user_pk) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/benutzer/PycharmProjects/X/venv/lib/python3.11/site-packages/nostr/key.py", line 93, in decrypt_message unpadded_data = unpadder.update(decrypted_message) + unpadder.finalize() ^^^^^^^^^^^^^^^^^^^ File "/home/benutzer/PycharmProjects/X/venv/lib64/python3.11/site-packages/cryptography/hazmat/primitives/padding.py", line 159, in finalize result = _byte_unpadding_check( ^^^^^^^^^^^^^^^^^^^^^^ File "/home/benutzer/PycharmProjects/X/venv/lib64/python3.11/site-packages/cryptography/hazmat/primitives/padding.py", line 101, in _byte_unpadding_check raise ValueError("Invalid padding bytes.") ValueError: Invalid padding bytes.

Am i doing this wrong or could this be a bug?

jeffthibault commented 1 year ago

One thing that jumps out is you are doing PrivateKey(), which creates a new private key object with a new secret. To decrypt the message, you need to be using the private key that corresponds to public key in the p tag of event_msg.event.

jeffthibault commented 1 year ago

Or you need to use the private key that corresponds to event_msg.event.public_key.

f321x commented 1 year ago

Oh ok makes sense, thanks. I'll try it.

f321x commented 1 year ago

Worked, my fault. Thanks for the help. Correct code in my case is:

private_key = PrivateKey().from_nsec("My nostr nsec private key")
...
if event_msg.event.kind == 4:
                user_pk = event_msg.event.public_key
                content = private_key.decrypt_message(event_msg.event.content, user_pk)
                print(content)