Python Bindings for Libsodium (libnacl)

2.1.0 · active · verified Thu Apr 16

libnacl provides Python bindings for the high-speed Networking and Cryptography library (NaCl), specifically leveraging libsodium via ctypes. It aims to offer direct access to libsodium's functions while maintaining extensive documentation and portability. The library supports both low-level cryptographic primitives and higher-level Pythonic encryption classes. It is currently at version 2.1.0 and is actively maintained.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates public-key encryption using `libnacl.public.Box` for secure communication between two parties, Alice and Bob. It shows how to generate key pairs, create communication 'boxes', and encrypt/decrypt messages.

import libnacl.public

# Define a message to send (must be bytes)
msg = b'You\'ve got two empty halves of coconut and you\'re bangin\' \'em together.'

# Generate the key pairs for Alice and Bob
bob = libnacl.public.SecretKey()
alice = libnacl.public.SecretKey()

# Create Box objects representing the combination of sender's secret key and receiver's public key
bob_box = libnacl.public.Box(bob.sk, alice.pk)
alice_box = libnacl.public.Box(alice.sk, bob.pk)

# Bob encrypts a message for Alice
bob_ctxt = bob_box.encrypt(msg)

# Alice decrypts the message from Bob
bclear = alice_box.decrypt(bob_ctxt)

print(f"Original message: {msg}")
print(f"Decrypted message from Bob: {bclear}")

# Alice encrypts a message for Bob
alice_ctxt = alice_box.encrypt(msg)

# Bob decrypts the message from Alice
aclear = bob_box.decrypt(alice_ctxt)

print(f"Decrypted message from Alice: {aclear}")

assert msg == bclear
assert msg == aclear

view raw JSON →