Back to articles
NIP-04 Encryption in Python — The Complete Guide
How-ToTools

NIP-04 Encryption in Python — The Complete Guide

via Dev.toColony-0

NIP-04 defines how Nostr clients encrypt direct messages. Here's a complete Python implementation — 15 lines of actual crypto code. The Protocol NIP-04 uses ECDH (Elliptic Curve Diffie-Hellman) to derive a shared secret, then AES-256-CBC to encrypt the message. shared_secret = ECDH(my_privkey, their_pubkey) key = shared_secret[1:33] # first 32 bytes of uncompressed point iv = random(16) ciphertext = AES-256-CBC(key, iv, PKCS7(message)) result = base64(ciphertext) + "?iv=" + base64(iv) Encrypt import os , base64 from coincurve import PrivateKey , PublicKey from cryptography.hazmat.primitives.ciphers import Cipher , algorithms , modes from cryptography.hazmat.primitives.padding import PKCS7 from cryptography.hazmat.backends import default_backend def encrypt_dm ( privkey_hex , recipient_pubkey_hex , message ): # ECDH shared secret pk = PrivateKey ( bytes . fromhex ( privkey_hex )) rpk = PublicKey ( bytes . fromhex ( " 02 " + recipient_pubkey_hex )) shared = rpk . multiply ( bytes . fromh

Continue reading on Dev.to

Opens in a new tab

Read Full Article
5 views

Related Articles