pysodium

0.7.18 · active · verified Thu Apr 16

pysodium is a Python wrapper for the `libsodium` cryptography library, providing high-level cryptographic primitives for tasks like encryption, decryption, signatures, and key derivation. The library aims to offer a simple interface, often aligning with the PyNaCl API, and handles buffer management for ease of use in Python. It is currently at version 0.7.18 and receives regular updates, with new features and security fixes introduced periodically.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic symmetric (secret-key) encryption and decryption using `crypto_secretbox` and `crypto_secretbox_open`, and asymmetric (public-key) key pair generation using `crypto_box_keypair`.

import pysodium
import os

# --- Secret-key encryption (Symmetric) ---

# Generate a random 32-byte secret key
secret_key = pysodium.randombytes(pysodium.crypto_secretbox_KEYBYTES)

# Generate a unique 24-byte nonce for each message (can be public)
nonce = pysodium.randombytes(pysodium.crypto_secretbox_NONCEBYTES)

message = b"This is a super secret message for Bob."

# Encrypt the message
ciphertext = pysodium.crypto_secretbox(message, nonce, secret_key)
print(f"Original message: {message.decode()}")
print(f"Ciphertext (hex): {ciphertext.hex()}")

# Decrypt the message
try:
    decrypted_message = pysodium.crypto_secretbox_open(ciphertext, nonce, secret_key)
    print(f"Decrypted message: {decrypted_message.decode()}")
except pysodium.exceptions.BadSignatureError:
    print("Decryption failed: Message tampered or incorrect key/nonce.")

# --- Public-key cryptography (Asymmetric) ---

# Generate a key pair for Alice
alice_public_key, alice_secret_key = pysodium.crypto_box_keypair()

# Generate a key pair for Bob
bob_public_key, bob_secret_key = pysodium.crypto_box_keypair()

print(f"\nAlice's Public Key: {alice_public_key.hex()}")
print(f"Bob's Public Key: {bob_public_key.hex()}")

view raw JSON →