libsodium

repository·master·Indexed 41 days ago

https://github.com/jedisct1/libsodium-doc

A high-level cryptographic library providing secure, easy-to-use primitives for encryption, signatures, and hashing. It includes APIs for generating random data, constant-time equality tests, hexadecimal and Base64 encoding, and little-endian arithmetic. Designed for portability and speed across major operating systems and programming languages.

Tokens
80.5K
Snippets
198
Records
297
Agent score
50%

What's inside libsodium

  1. Overview of the crypto_ipcrypt API

    master

    The crypto_ipcrypt API provides efficient, secure, and reversible encryption for IPv4 and IPv6 addresses. It is designed for privacy-preserving storage, logging, and analytics, allowing you to protect IP addresses while maintaining the ability to decrypt them when necessary.

    Key benefits include:

    • Reversibility: Unlike hashing, you can recover the original IP.
    • Operational Utility: Supports various modes for database indexing, rate limiting, or anonymized data sharing.
  2. Overview of the libsodium crypto library

    master
    libsodium (Sodium) is a modern, portable, and cross-compilable software library designed for high-security cryptographic operations. It provides primitives for encryption, decryption, digital signatures, and password hashing. It is a fork of NaCl with an extended API designed to improve usability while maintaining high performance across various platforms.
  3. Applications using libsodium

    master

    Libsodium is used by a wide variety of production-grade applications across different domains, including messaging, blockchain, VPNs, and security tools. Notable examples include:

    • Communication & Chat: Discord, Wire, Tox, Cyph, emberclear, NanoChat.
    • Security & Password Management: KeepassXC, PAVE, PassVault, Secrets, Kickpass.
    • Blockchain & Decentralized Tech: Zcash, Tezos, Stellar, Apache Tuweni, Duniter.
    • Networking & VPNs: ShadowSocks, Glorytun, Husarnet, Muon, MLVPN.
    • Infrastructure & Tools: OpenSSH, SaltStack, Dovecot, PowerDNS, Vim (for encrypted files).

    If you are developing an application that uses libsodium, you can contribute to this list by submitting a pull request.

  4. What is Ristretto255?

    master

    Ristretto255 is a unified point compression format for curves over large-characteristic fields. It implements a prime-order group by dividing the curve's cofactor by 4 or 8 with minimal performance cost.

    In libsodium (version 1.0.18+), ristretto255 is implemented on top of the Curve25519 curve. It makes it easier to safely implement protocols originally designed for prime-order groups compared to using Curve25519 points encoded as coordinates.

  5. What is XSalsa20 and when to use it

    master

    XSalsa20 is a stream cipher based on Salsa20 that uses a 192-bit nonce (compared to Salsa20's 64-bit nonce) and a 256-bit key.

    Key Advantages:

    • Nonce Safety: Because the nonce is 192 bits, it is safe to generate nonces using randombytes_buf() for every message encrypted with the same key without worrying about collisions.
    • Security: It is immune to timing attacks and includes its own 64-bit block counter to avoid the need for manual nonce incrementing after each block.

    Warning: XSalsa20 (via crypto_stream_xor) provides confidentiality but not authentication. It does not include an authentication tag. For authenticated encryption, consider using an AEAD construction.

  6. What is XChaCha20 and when to use it

    master

    XChaCha20 is a variant of the ChaCha20 stream cipher featuring an extended 192-bit nonce.

    Key Characteristics:

    • Safe Random Nonces: Because the nonce is 192 bits long, it is safe to generate a random nonce for every message. The probability of a collision is negligible.
    • Security: It avoids lookup tables, making it resistant to timing attacks.
    • Performance: It offers comparable performance to standard ChaCha20.
    • Recommendation: XChaCha20 is generally recommended over plain ChaCha20 due to the extended nonce size, though it is less widely implemented outside of libsodium due to the lack of a formal specification.
  7. Use Sealed Boxes for anonymous message encryption

    master

    Sealed boxes allow a sender to encrypt a message for a recipient using only the recipient's public key. This provides anonymity because the sender uses an ephemeral key pair that is erased immediately after encryption, meaning the sender cannot decrypt the message later and the recipient cannot verify the sender's identity from the ciphertext alone.

    Key Characteristics:

    • Anonymity: The sender's identity cannot be correlated with the message without additional data.
    • One-way: The sender cannot decrypt the message once it is sent.
    • Integrity: The recipient can verify the integrity of the message.
    • Compatibility: Uses standard crypto_box key pairs (X25519 and XSalsa20-Poly1305).
    /* Recipient creates a long-term key pair */
    unsigned char recipient_pk[crypto_box_PUBLICKEYBYTES];
    unsigned char recipient_sk[crypto_box_SECRETKEYBYTES];
    crypto_box_keypair(recipient_pk, recipient_sk);
    
    /* Anonymous sender encrypts a message using an ephemeral key pair
     * and the recipient's public key */
    unsigned char ciphertext[CIPHERTEXT_LEN];
    crypto_box_seal(ciphertext, MESSAGE, MESSAGE_LEN, recipient_pk);
    
    /* Recipient decrypts the ciphertext */
    unsigned char decrypted[MESSAGE_LEN];
    if (crypto_box_seal_open(decrypted, ciphertext, CIPHERTEXT_LEN,
                             recipient_pk, recipient_sk) != 0) {
        /* message corrupted or not intended for this recipient */
    }
  8. Preventing Nonce Reuse in Salsa20

    master

    Salsa20 uses a 64-bit nonce. Reusing a nonce with the same key is dangerous. To prevent reuse:

    1. Increment the nonce: If you are reusing a key, increment the previous nonce for each new stream instead of generating a random one.
    2. Use XSalsa20: Use the XSalsa20 variant, which features an extended nonce construction, making it easier to safely generate nonces.
  9. Choosing a XOF variant

    master

    Extendable Output Functions (XOFs) allow you to produce an arbitrary amount of output from a fixed-length input. The choice of variant depends on your security requirements and performance needs.

    TurboSHAKE128 is the recommended variant for most applications. It provides:

    • High performance (~2x faster than SHAKE).
    • 128-bit security.
    • Built-in domain separation support.
    • Standardization via RFC 9861.

    Alternative Variants

    • SHAKE256 or TurboSHAKE256: Use these when you require 256-bit collision resistance.
    • SHAKE128 or SHAKE256: Use these when NIST FIPS 202 compliance is mandated.

    Note: The numbers '128' and '256' refer to the security level, not the output size. All variants can produce output of any length.

  10. Authenticated Encryption with Additional Data (AEAD) using ChaCha20-Poly1305

    master

    ChaCha20-Poly1305 is an Authenticated Encryption with Additional Data (AEAD) construction. It provides both confidentiality (encryption) and integrity (authentication).

    Key Features:

    • Confidentiality: Encrypts a message using a key and a nonce.
    • Integrity/Authenticity: Computes an authentication tag to ensure the message and any optional, non-confidential 'additional data' have not been tampered with.
    • Security Model: Uses an encrypt-then-MAC construction. Decryption is never performed partially before verification is complete.
    • Additional Data: Can be used to include protocol-specific metadata (like length or encoding) that remains unencrypted but is protected against tampering.
  11. Security requirements for Poly1305 keys

    master

    Poly1305 is a Wegman-Carter authenticator used for one-time authentication. Because it is a one-time authenticator, the security of the system relies entirely on the properties of the key.

    Key Requirements:

    • Secret: The key must remain unknown to attackers.
    • Unpredictable: Do not use timestamps or counters to generate keys.
    • Unique (One-time use): Never reuse a key. A new key must be used for every single message. Reusing a key for two different messages allows the key to be recovered.

    Best Practice: Derive a dedicated subkey from a (key, nonce) tuple (e.g., using the first bytes generated by a stream cipher) for each message.

    Limitations:

    • Poly1305 is recommended for online protocols and exchanging many small messages. It is not recommended for authenticating very large files due to its output size.
    • Poly1305 is not a replacement for a hash function.
  12. How finite field arithmetic works in libsodium

    master

    The crypto_core_ed25519_* APIs provide low-level computations over the edwards25519 curve. These are intended for implementing custom cryptographic constructions rather than general-purpose use.

    Key Mental Models:

    • Point Representation: Points on the curve are represented by their Y coordinate.
    • Scalar Arithmetic: Scalar operations (addition, subtraction, multiplication, inversion) are performed over the interval [0..L[, where L is the order of the main subgroup.
    • Clamping vs. No-Clamping: Standard scalar multiplication functions (crypto_scalarmult_ed25519) 'clamp' the scalar (clearing low bits and setting specific high bits) to prevent small-subgroup attacks. If your protocol requires the scalar to be invertible or requires exact values, use the _noclamp variants, which expect scalars in the ]0..L[ range.