Skip to content

Instantly share code, notes, and snippets.

@oconnor663
Created July 8, 2015 20:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oconnor663/aa27fe8cf01e05d1d759 to your computer and use it in GitHub Desktop.
Save oconnor663/aa27fe8cf01e05d1d759 to your computer and use it in GitHub Desktop.
Equivalent key with different bytes in PyNaCl
import nacl.utils
import nacl.public
sender_key = nacl.public.PrivateKey.generate()
recipient_key_1 = nacl.public.PrivateKey.generate()
# Construct the second recipient by changing one bit from the first.
key_bytes = bytearray(recipient_key_1.encode())
key_bytes[0] ^= 1
recipient_key_2 = nacl.public.PrivateKey(bytes(key_bytes))
if recipient_key_1.encode() != recipient_key_2.encode():
print("The two recipients have different private keys.")
if recipient_key_1.public_key.encode() == recipient_key_2.public_key.encode():
print("But their public keys are the same!")
# Encrypt a plaintext for recipient *one*.
plaintext = b"FOR YOUR EYES ONLY"
sender_box = nacl.public.Box(sender_key, recipient_key_1.public_key)
nonce = nacl.utils.random(nacl.public.Box.NONCE_SIZE)
ciphertext = sender_box.encrypt(plaintext, nonce)
# Decrypt it as recipient *two*.
recipient_box = nacl.public.Box(recipient_key_2, sender_key.public_key)
decrypted = recipient_box.decrypt(ciphertext)
if decrypted == plaintext:
print("And they can read each other's messages!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment