ChaCha20Poly1305 Reusable for Asyncio

0.13.2 · deprecated · verified Thu Apr 16

This library provides a Python implementation of the ChaCha20Poly1305 authenticated encryption algorithm, specifically designed for asynchronous I/O (asyncio) contexts. While it aimed to offer a reusable cipher object for efficiency, it is now considered obsolete for new projects due to the `cryptography` library's adoption of a high-performance, Rust-based ChaCha20Poly1305 implementation. The library is currently at version 0.13.2, with recent maintenance releases, but its utility for new development is superseded.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the `ChaCha20Poly1305Reusable` cipher with a 32-byte key, encrypt plaintext with optional associated data (AAD), and then decrypt it, verifying integrity. It highlights how the cipher object itself can be reused, but crucially, a new cryptographic nonce is generated and required for each distinct encryption operation.

import os
from chacha20poly1305_reuseable import ChaCha20Poly1305Reusable

# In a real application, securely load your key (32 bytes).
# For demonstration, a random key is generated.
key = os.urandom(32)

# Associated data (AAD) is optional, but recommended for integrity checks.
associated_data = b"Config data, not encrypted but authenticated."
plaintext = b"This is the secret message to be encrypted."

# Initialize the cipher object with the key
cipher = ChaCha20Poly1305Reusable(key)

# Encrypt the plaintext
# The nonce is generated internally and returned, must be unique per encryption.
nonce, ciphertext, tag = cipher.encrypt(plaintext, associated_data)
print(f"Encryption successful:")
print(f"  Nonce: {nonce.hex()}")
print(f"  Ciphertext: {ciphertext.hex()}")
print(f"  Tag: {tag.hex()}")

# Decrypt the ciphertext
try:
    decrypted_text = cipher.decrypt(nonce, ciphertext, tag, associated_data)
    print(f"Decryption successful: {decrypted_text.decode()}")
    assert decrypted_text == plaintext
    print("Message integrity verified.")
except Exception as e:
    print(f"Decryption failed: {e}")

# The 'cipher' object can be reused for subsequent encryptions/decryptions
# with a *new*, unique nonce for each operation.
new_plaintext = b"Another secret message, secured by the same key."
new_nonce, new_ciphertext, new_tag = cipher.encrypt(new_plaintext, associated_data)
print(f"\nReused cipher for new encryption (new nonce): {new_nonce.hex()}")

view raw JSON →