Skip to content

Instantly share code, notes, and snippets.

@kakopappa
Created October 17, 2024 04:25
Show Gist options
  • Save kakopappa/c2d983969e81cca2de790a3db87e6f2f to your computer and use it in GitHub Desktop.
Save kakopappa/c2d983969e81cca2de790a3db87e6f2f to your computer and use it in GitHub Desktop.
XSalsa20-Poly1305 Encryption Example
import nacl.utils
from nacl.public import PrivateKey, Box
from nacl.secret import SecretBox
import nacl.bindings
def generate_keypair():
private_key = PrivateKey.generate()
public_key = private_key.public_key
return private_key, public_key
def perform_key_exchange(private_key, other_public_key):
shared_key = Box(private_key, other_public_key).shared_key()
return shared_key
def derive_key_hsalsa20(shared_key, nonce):
derived_key = nacl.bindings.crypto_core_hsalsa20(shared_key, nonce)
return derived_key
def encrypt_message(key, message):
# Create a SecretBox with our key
box = SecretBox(key)
# Encrypt the message
encrypted = box.encrypt(message.encode())
return encrypted
def decrypt_message(key, encrypted):
# Create a SecretBox with our key
box = SecretBox(key)
# Decrypt the message
decrypted = box.decrypt(encrypted)
return decrypted.decode()
# Example usage
if __name__ == "__main__":
# Generate keypairs for Alice and Bob
alice_private, alice_public = generate_keypair()
bob_private, bob_public = generate_keypair()
# Perform key exchange
alice_shared = perform_key_exchange(alice_private, bob_public)
bob_shared = perform_key_exchange(bob_private, alice_public)
# Generate a nonce for key derivation
kdf_nonce = nacl.utils.random(16)
# Derive keys using HSalsa20
alice_derived_key = derive_key_hsalsa20(alice_shared, kdf_nonce)
bob_derived_key = derive_key_hsalsa20(bob_shared, kdf_nonce)
# Alice encrypts a message
message = "Hello, Bob! This is a secret message."
encrypted = encrypt_message(alice_derived_key, message)
# Bob decrypts the message
decrypted = decrypt_message(bob_derived_key, encrypted)
print("Original message:", message)
print("Encrypted message:", encrypted.hex())
print("Decrypted message:", decrypted)
print("Decryption successful:", message == decrypted)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment