> For the complete documentation index, see [llms.txt](https://libsodium.gitbook.io/doc/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://libsodium.gitbook.io/doc/quickstart.md). Agents can also search and read this documentation through its [MCP server](https://libsodium.gitbook.io/doc/~gitbook/mcp).

# Quickstart and FAQ

## Boilerplate

A project using libsodium should include the `sodium.h` header. Including individual headers is neither required nor recommended.

The `sodium_init()` function must be called before any other function. It is safe to call `sodium_init()` multiple times or from different threads; it will immediately return `1` without doing anything if the library has already been initialized.

```c
#include <sodium.h>

int main(void)
{
    if (sodium_init() < 0) {
        /* panic! the library couldn't be initialized; it is not safe to use */
    }
    return 0;
}
```

## What is the difference between point releases and stable releases?

Libsodium uses a two-tier versioning system.

**Point releases** (like 1.0.20, 1.0.21, 1.0.22) are tagged when new features are added or significant changes are made.

**Stable releases** happen more frequently between point releases. They fix compilation issues, improve documentation, and enhance performance while remaining fully compatible with their parent point release. They never introduce new features or breaking changes.

If your application depends on a specific point release, you can safely apply stable updates without worrying about compatibility. This is valuable for enterprises that need continuous support without surprises. Of course, you can also choose to use only point releases if you prefer.

If a security issue is discovered, it gets fixed in the stable branch of all supported versions, and a new point release follows shortly after.

See the [Installation guide](https://libsodium.gitbook.io/doc/installation.md#versioning) for more details.

## Is libsodium cross-platform?

Yes, a message can be encrypted in Python on a MIPS CPU, decrypted in JavaScript using Chrome on Windows, and its signature can then be verified by an iPhone app written in Swift.

The available algorithms are the same on all supported platforms, input and output formats are also identical on all platforms, and bindings for various programming languages tend to leverage the original algorithms and formats.

## How do I generate random numbers that are safe to use for cryptography?

Use the [`randombytes` API](https://libsodium.gitbook.io/doc/generating_random_data.md).

## How do I compute a hash?

Use the [`crypto_generichash` API](https://libsodium.gitbook.io/doc/hashing/generic_hashing.md).

## What is the difference between a secret key and a password?

A password has a couple of requirements to fulfill:

* It has to be reasonably short.
* It must be easy to type on any keyboard.
* Users may have to remember it.

As a result, the number of possible passwords of a given size is fairly small. For the same size, the number of distinct passwords actually used is much smaller, and their distribution is skewed. Even if mitigations exist, guessing (brute-forcing) a password is often practical.

A secret key, on the other hand, is a sequence of bits that can be of any size, doesn’t have any restrictions, and is generated by software or specialized hardware. A 32-byte key represents 256 bits, none of them being predictable by observing other bits from that key or previous keys.

Secret keys are not designed to be typed on a keyboard. They are binary data stored as files, kept in secure memory, or sent over the network. They can be unique and offer far more security than passwords.

Libsodium almost exclusively uses secret keys.

If an application must use a password as a secret key, it should call the `crypto_pwhash()` function first. This computes a secret key from a password using an intentionally CPU-intensive and memory-hard function to slow down brute-force attacks.

Native secret keys using the `*_keygen()` function should always be preferred.

## How do I initialize the library from another library?

If the other library doesn’t have any initialization function, it can use a [`DllMain()`](https://learn.microsoft.com/en-us/windows/win32/dlls/dllmain) function (Windows) or `__attribute__((constructor))` (GCC, Clang, icc on macOS and ELF-based systems) to call `sodium_init()` on load.

However, explicitly calling initialization functions is recommended as automatic initialization makes it difficult to safely recover from errors.

## How do I check if a function call succeeded?

Functions returning an `int` return `0` on success and `-1` to indicate an error.

Functions returning a pointer return a valid address on success and `NULL` on error.

Some operations include variants with slightly different algorithms. For example, authenticated encryption can be done with XChaCha20-Poly1305 or AES-GCM. For consistency and to make high-level wrappers using dynamic dispatch easier to implement, all the variants of a function share the same prototype.

In the above example, AES-GCM can fail due to message size limits, but XChaCha20 cannot; its limits are only theoretical, so checking the return value for that variant would not be strictly necessary. However, it is best to check unconditionally in applications because it is cheap, good hygiene, and functions can easily be replaced later if necessary.

Some returned values must be checked. For example, the outcome of the verification of an authentication token. These functions are tagged with the `warn_unused_result` attribute and will cause a compiler warning if ignored. Such warnings must not be ignored.

## How do I encrypt data?

If you have the recipient’s public key but no shared secret, use [key encapsulation followed by authenticated encryption](#how-can-a-and-b-securely-communicate-without-a-pre-shared-secret-key).

If you can already share a secret key securely, no key encapsulation is needed.

### One-shot encryption where everything fits in memory

1. Create a secret key using `crypto_secretbox_keygen()`.
2. Create a nonce using `randombytes_buf(nonce, sizeof nonce)`.
3. Use `crypto_secretbox_easy()` to encrypt the message and send/store the resulting ciphertext along with the nonce. Unlike the key, the nonce doesn’t have to be secret.
4. Use `crypto_secretbox_open_easy()` to decrypt the ciphertext using the same key and nonce.

### If everything doesn’t fit in memory or is not available as a single chunk

* With libsodium 1.0.14 and beyond, use the [`crypto_secretstream` API](https://libsodium.gitbook.io/doc/secret-key_cryptography/secretstream.md).
* Otherwise, read the guidance on [encrypting a set of messages](https://libsodium.gitbook.io/doc/secret-key_cryptography/encrypted-messages.md).

## How do I safely store and later verify a password?

* Use the `crypto_pwhash_str()` and `crypto_pwhash_str_verify()` functions described in the [`password hashing guide`](https://libsodium.gitbook.io/doc/password_hashing.md).

## How do I encrypt a file using a password?

1. Derive an encryption key from the password using [`crypto_pwhash()`](https://libsodium.gitbook.io/doc/password_hashing/default_phf.md).
2. Use that key with the [`crypto_secretstream` API](https://libsodium.gitbook.io/doc/secret-key_cryptography/secretstream.md).

Secret file metadata should be part of the encrypted data, and non-secret metadata can be included as additional data.

## How can `A` and `B` securely communicate without a pre-shared secret key?

For new applications, use the [`crypto_kem` API](https://libsodium.gitbook.io/doc/public-key_cryptography/key_encapsulation.md) (libsodium 1.0.22 or later) to establish a shared secret, then encrypt the message with that secret.

The KEM uses X-Wing, which combines ML-KEM768 with X25519.

1. `B` generates a recipient key pair with `crypto_kem_keypair(pk, sk)` and keeps `sk` secret. `A` needs an authentic copy of `B`’s public key, for example one whose fingerprint they have checked with `B`.
2. `A` calls `crypto_kem_enc(ct, key, pk)`. On success, `A` has a fresh shared key and a KEM ciphertext `ct`. The KEM ciphertext encapsulates the key, not the message.
3. `A` encrypts the message with `key` using an [AEAD](https://libsodium.gitbook.io/doc/secret-key_cryptography/aead.md) such as XChaCha20-Poly1305, or [`crypto_secretbox_easy()`](https://libsodium.gitbook.io/doc/secret-key_cryptography/secretbox.md). For either of these two constructions, `A` can generate a fresh random 24-byte nonce with `randombytes_buf()`. `A` sends `ct`, the nonce, and the authenticated message ciphertext to `B`, but never sends `key`.
4. `B` calls `crypto_kem_dec(key, ct, sk)` to recover the same key and uses the matching decryption function with that key and nonce. If decapsulation or authenticated decryption fails, reject the message.

For a two-way exchange, use [`crypto_kdf_derive_from_key()`](https://libsodium.gitbook.io/doc/key_derivation.md) with the shared secret as the master key.

Both peers use the same context and assign a different subkey ID to each direction.

Never reuse a nonce with the same encryption key.

The X25519-only [key exchange API (`crypto_kx`)](https://libsodium.gitbook.io/doc/classical_cryptography/key_exchange.md), [`crypto_box`](https://libsodium.gitbook.io/doc/classical_cryptography/authenticated_encryption.md), and [sealed boxes](https://libsodium.gitbook.io/doc/classical_cryptography/sealed_boxes.md) are [classical cryptography](https://libsodium.gitbook.io/doc/classical_cryptography.md), not post-quantum alternatives to `crypto_kem`.

## How can I derive multiple keys from a single master key like what HKDF does?

Use the [key derivation API](https://libsodium.gitbook.io/doc/key_derivation.md).

## Do I need to add a signature to encrypted messages to detect if they have been tampered with?

No. An AEAD or `crypto_secretbox` already includes an authentication tag.

Decryption checks the tag and fails if the ciphertext has been modified.

With an AEAD, the tag also covers the associated data, such as an unencrypted message header.

A valid tag does not by itself identify the sender.

Anyone with `B`’s public KEM key can encapsulate a fresh key and use it to send `B` a valid encrypted message.

If `B` needs proof that `A` sent it, use a protocol that authenticates `A`, for example by verifying a signature with a trusted signing public key.

This distinction also matters for [messages sent to multiple recipients](https://github.com/jedisct1/libsodium-doc/tree/master/quickstart/multiple_recipients.md).

## How can I sign and encrypt using the same key pair?

Use separate key pairs. Generate a KEM key pair for encryption and a signing key pair for signatures.

The keys have different formats and can then be rotated independently.

The [Ed25519 to X25519 conversion](https://libsodium.gitbook.io/doc/classical_cryptography/ed25519-curve25519.md) applies only to classical keys.

It does not produce a `crypto_kem` key pair.

Libsodium’s [Ed25519 signatures](https://libsodium.gitbook.io/doc/classical_cryptography/public-key_signatures.md) are also classical: using them alongside a hybrid KEM does not make the signatures post-quantum.

## How do I hide the length of a message?

Use [padding](https://libsodium.gitbook.io/doc/padding.md).

## Should I call `crypto_generichash_blake2b` or just `crypto_generichash`?

Always use the high-level API if one is available. The low-level API it is based on is guaranteed not to change before a major revision of the library. If a high-level API needs to use a different construction, it will expose a different set of functions.

This is true for all APIs provided by this library.

## Why is `crypto_stream()` barely documented and not even present in some bindings?

The `crypto_stream()` API generates a deterministic sequence of bytes from a seed and optionally applies the XOR operation between that sequence and some input sequence.

Performing the XOR operation once produces content that resembles random data, and performing the same operation twice restores the initial input sequence.

This can be seen as a form of encryption. However,

* If an adversary replaces the ciphertext with null bytes, the original, complete sequence derived from the seed will be decrypted. This can have catastrophic implications with some (badly designed) protocols.
* More generally, anyone can modify the ciphertext without this being detected. Since a stream cipher is XOR’d with a message, targeted bits can be flipped. Knowing the secret key is not required.

If a deterministic sequence must be derived from a seed (e.g. for unit testing), libsodium provides the `randombytes_buf_deterministic()` function.

For actual encryption, other options such as `crypto_secretbox`, `crypto_aead`, and `crypto_secretstream` should be used over `crypto_stream` as they will add and verify an authentication tag to detect data that has been corrupted or tampered with.

`crypto_stream()` is only useful as a building block to design custom constructions. As-is, it is completely insecure.

## Is encryption without nonces possible?

The encryption schemes implemented in libsodium are fast but require a unique `(key, nonce)` tuple for every message.

Nonces don’t have to be secret, but they must not be reused. Reusing a nonce would destroy the confidentiality of messages sharing the same nonce and allow an attacker to craft additional valid ciphertexts.

On a platform where counters cannot be maintained and no trusted source of randomness exists, deterministic encryption can be used as a last resort.

[XChaCha20-SIV](https://github.com/jedisct1/libsodium-xchacha20-siv) is such a construction, which can also be used for key wrapping.

On such systems, [libhydrogen](https://libhydrogen.org) may also be a better option.

## I want to write bindings for my favorite language, where should I start?

Start with the `crypto_generichash` and `crypto_secretstream` APIs. These are the trickiest to write bindings for and will provide good insights into how to design your bindings.

## Notes

The X-Wing and symmetric encryption combination above is designed for post-quantum confidentiality.
