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.
pip install libnaclVerified import paths — ran on the pinned version, not inferred.
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.
Prefer higher-level `Box` or `SecretBox` classes which abstract away padding details. If using raw `crypto_secretbox`, ensure message conforms to `libsodium`'s padding requirements (e.g., pre-pending 32 null bytes if required by the specific libsodium version/implementation for MAC key).
Always ensure a unique nonce is used for each message encrypted with the same key pair. For high-level APIs like `Box.encrypt()`, a random nonce is generated by default. If manually generating, use `libnacl.utils.rand_nonce()` or a cryptographically secure random source and track nonce usage carefully.
Install the `libsodium` development headers and runtime library through your system's package manager (e.g., `sudo apt-get install libsodium-dev` on Debian/Ubuntu, `brew install libsodium` on macOS, or `vcpkg install libsodium` on Windows).
Install `libsodium` via your system's package manager. For Debian/Ubuntu, use `sudo apt-get install libsodium-dev`. Ensure the library is accessible in your system's `LD_LIBRARY_PATH` (Linux) or `PATH` (Windows) if installed in a non-standard location.
First, ensure `libsodium` is correctly installed on your system (see above fix). Then, try reinstalling `libnacl` in your Python environment: `pip uninstall libnacl && pip install libnacl`.
Verify that the correct secret key, public key, and nonce (if applicable) are being used for decryption. Ensure the ciphertext has not been tampered with in transit. This error is a security feature, indicating a failed authenticity check.