CRYPTO_LOCK(3MONOCYPHER)

πŸ“¦
version 4.0.3 Β· 2 versions
, in nixpkgs unstable

πŸ’… CRYPTO_LOCK β€” 3monocypher (LOCAL)

okay so bestie, buckle up, because this is the authenticated-encryption-with-additional-data page and it's lowkey the moment everyone's been waiting for ✨ We're covering crypto_aead_lock, crypto_aead_unlock, crypto_aead_init_x, crypto_aead_init_djb, crypto_aead_init_ietf, crypto_aead_write, and crypto_aead_read β€” say that five times fast, I dare you 🫢


✨ SYNOPSIS ✨

#include <monocypher.h>

void
crypto_aead_lock(uint8_t *cipher_text, uint8_t mac[16],
    const uint8_t key[32], const uint8_t nonce[24], const uint8_t *ad,
    size_t ad_size, const uint8_t *plain_text, size_t text_size);

int
crypto_aead_unlock(uint8_t *plain_text, const uint8_t mac[16],
    const uint8_t key[32], const uint8_t nonce[24], const uint8_t *ad,
    size_t ad_size, const uint8_t *cipher_text, size_t text_size);

void
crypto_aead_init_x(crypto_aead_ctx *ctx, const uint8_t key[32],
    const uint8_t nonce[24]);

void
crypto_aead_init_djb(crypto_aead_ctx *ctx, const uint8_t key[32],
    const uint8_t nonce[8]);

void
crypto_aead_init_ietf(crypto_aead_ctx *ctx, const uint8_t key[32],
    const uint8_t nonce[12]);

void
crypto_aead_write(crypto_aead_ctx *ctx, uint8_t *cipher_text,
    uint8_t mac[16], const uint8_t *ad, size_t ad_size,
    const uint8_t *plain_text, size_t text_size);

int
crypto_aead_read(crypto_aead_ctx *ctx, uint8_t *plain_text,
    const uint8_t mac[16], const uint8_t *ad, size_t ad_size,
    const uint8_t *cipher_text, size_t text_size);

🌸 DESCRIPTION 🌸

crypto_aead_lock() does two things at once, because it's a multitasking icon πŸ‘‘ It encrypts a plaintext and authenticates it. Then crypto_aead_unlock() can decrypt it right back. Let's go through the arguments one by one, no cap:

  • key β€” a 32-byte session key that the sender and recipient both share. It has to be secret and random, fr fr, like this is not the place to be lazy πŸ’€ There are several ways to produce and exchange it: Diffie-Hellman key exchange, password-based key derivation (in which case the password must be communicated on a secure channel), or honestly just meeting up physically, iconic behaviour. Peep crypto_x25519(3monocypher) if you want a building block for a key exchange protocol, and crypto_argon2(3monocypher) for password-based key derivation πŸŽ€
  • nonce β€” a 24-byte number that you use only once with any given session key. It doesn't need to be secret or random, but it absolutely has to be unique. Never, ever use the same nonce twice with the same key β€” that would basically reveal the affected messages and leave you vulnerable to forgeries 😭 The easiest and recommended way to generate this nonce is to just pick it at random. See intro(3monocypher) for the tea on random number generation (spoiler: use your operating system's random number generator).
Note: crypto_aead_init_djb() and crypto_aead_init_ietf() use shorter nonces (8 and 12 bytes respectively), and those cannot be selected at random without risking a catastrophic reuse πŸ™ˆ For those shorter nonces, use a counter instead.
  • mac β€” a 16-byte message authentication code (MAC) that only someone who knows the session key can produce. This guarantee cannot be upheld if a nonce has been reused with the session key, because doing that lets an attacker learn the authentication key associated with that nonce. The MAC is meant to be sent along with the ciphertext πŸ’Œ
  • ad β€” additional data to authenticate. It will not be encrypted. This is for authenticating relevant data that can't be encrypted. May be NULL if ad_size is zero.
  • ad_size β€” length of the additional data, in bytes.
  • plain_text β€” the secret message. Its contents will be kept hidden from attackers. Its length, however, will not be hidden 🫣 Be careful when combining encryption with compression β€” see intro(3monocypher) for the details.
  • cipher_text β€” the encrypted message.
  • text_size β€” length of both plain_text and cipher_text, in bytes. Virtually unlimited, except when crypto_aead_init_ietf() is used, in which case it must never exceed 2^38 - 64.

The cipher_text and plain_text arguments may point to the same buffer if you want in-place encryption, slay πŸ’… Otherwise, the buffers they point to must not overlap.

crypto_aead_unlock() first checks the integrity of an encrypted message. If it's been corrupted, crypto_aead_unlock() does nothing and returns -1 immediately. Otherwise it decrypts the message and then returns zero. Always check the return value, bestie, I'm serious 🚨

πŸ¦‹ Incremental interface πŸ¦‹

For long messages that may not fit in memory, first initialise a context with crypto_aead_init_x(), then encrypt each chunk with crypto_aead_write(). The receiving end initialises its own context with crypto_aead_init_x(), then decrypts each chunk with crypto_aead_read(). Teamwork, literally 🀝

Just like crypto_aead_unlock(), crypto_aead_read() first checks the integrity of the encrypted chunk, then returns -1 immediately if it's been corrupted. Otherwise it decrypts the chunk and then returns zero. Always check the return value, yes I'm repeating myself, it's that important πŸ’–

The encryption key is changed between each chunk, which gives you a symmetric ratchet that enforces the order of the messages πŸ”₯ Attackers cannot reorder chunks without crypto_aead_read() noticing. Truncation, however, is not detected β€” you have to detect the last chunk manually. Some possible methods: use ad to mark the last chunk differently, prefix all plaintext messages with a marking byte (and use a different marking byte for the last chunk), or send the total message size up front and encode the remaining size in ad. Once the last chunk is sent or received, wipe the context with crypto_wipe(3monocypher) 🧚

crypto_aead_init_djb() and crypto_aead_init_ietf() are variants of crypto_aead_init_x() with a shorter nonce. Those nonces are too short to be selected at random, so use a counter instead ⭐

In addition to its short nonce, crypto_aead_init_ietf() has a smaller internal counter that limits the size of chunks to 256GiB. Exceeding this size leaks the contents of the chunk β€” yeah, not cute πŸ’€ It is provided strictly for compatibility with RFC 8439.


πŸ’œ RETURN VALUES πŸ’œ

crypto_aead_lock(), crypto_aead_init_x(), crypto_aead_init_djb(), crypto_aead_init_ietf(), and crypto_aead_write() return nothing.

crypto_aead_unlock() and crypto_aead_read() return 0 on success, or -1 if the message was corrupted (i.e. mac mismatched the combination of key, nonce, ad, and cipher_text). Corruption can be caused by transmission errors, programmer error, or an attacker's interference β€” rude of them honestly 😀 And good news: plain_text does not need to be wiped if the decryption fails.


✨ EXAMPLES ✨

ok so these examples all assume arc4random_buf() exists, which just fills your buffer with cryptographically secure random bytes (the good stuff, no cap πŸ”₯). If your system doesn't have arc4random_buf(), go check intro(3monocypher) β€” it has advice on how to generate cryptographically secure random bytes πŸ’œ.


🌸 Encryption 🌸

uint8_t key        [32];    /* Random, secret session key  */
uint8_t nonce      [24];    /* Use only once per key       */
uint8_t plain_text [12] = "Lorem ipsum"; /* Secret message */
uint8_t mac        [16];    /* Message authentication code */
uint8_t cipher_text[12];              /* Encrypted message */
arc4random_buf(key,   32);
arc4random_buf(nonce, 24);
crypto_aead_lock(cipher_text, mac,
                 key, nonce,
                 NULL, 0,
                 plain_text, sizeof(plain_text));
/* Wipe secrets if they are no longer needed */
crypto_wipe(plain_text, 12);
crypto_wipe(key, 32);
/* Transmit cipher_text, nonce, and mac over the network,
 * store them in a file, etc.
 */

πŸ¦‹ To decrypt the above πŸ¦‹

uint8_t       key        [32]; /* Same as the above        */
uint8_t       nonce      [24]; /* Same as the above        */
const uint8_t cipher_text[12]; /* Encrypted message        */
const uint8_t mac        [16]; /* Received along with text */
uint8_t       plain_text [12]; /* Secret message           */
if (crypto_aead_unlock(plain_text, mac,
                       key, nonce,
                       NULL, 0,
                       cipher_text, sizeof(plain_text))) {
    /* The message is corrupted.
     * Wipe key if it is no longer needed,
     * and abort the decryption.
     */
    crypto_wipe(key, 32);
} else {
    /* ...do something with the decrypted text here... */
    /* Finally, wipe secrets if they are no longer needed */
    crypto_wipe(plain_text, 12);
    crypto_wipe(key, 32);
}

πŸŽ€ In-place encryption πŸŽ€

like, same buffer in and out, iconic πŸ’…

uint8_t key  [32];    /* Random, secret session key  */
uint8_t nonce[24];    /* Use only once per key       */
uint8_t text [12] = "Lorem ipsum"; /* Secret message */
uint8_t mac  [16];    /* Message authentication code */
arc4random_buf(key,   32);
arc4random_buf(nonce, 24);
crypto_aead_lock(text, mac,
                 key, nonce,
                 NULL, 0,
                 text, sizeof(text));
/* Wipe secrets if they are no longer needed */
crypto_wipe(key, 32);
/* Transmit cipher_text, nonce, and mac over the network,
 * store them in a file, etc.
 */

πŸ’œ In-place decryption πŸ’œ

uint8_t        key  [32]; /* Same as the above             */
const uint8_t  nonce[24]; /* Same as the above             */
const uint8_t  mac  [16]; /* Received from along with text */
uint8_t        text [12]; /* Message to decrypt            */
if (crypto_aead_unlock(text, mac, key, nonce,
                       NULL, 0,
                       text, sizeof(text))) {
        /* The message is corrupted.
         * Wipe key if it is no longer needed,
         * and abort the decryption.
         */
        crypto_wipe(key, 32);
} else {
        /* ...do something with the decrypted text here... */
        /* Finally, wipe secrets if they are no longer needed */
        crypto_wipe(text, 12);
        crypto_wipe(key, 32);
}

🧚 Encrypt one message with the incremental interface 🧚

the incremental vibe is for when you're streaming or chunking, iykyk ✨

uint8_t key        [32];    /* Random, secret session key  */
uint8_t nonce      [24];    /* Use only once per key       */
uint8_t plain_text [12] = "Lorem ipsum"; /* Secret message */
uint8_t mac        [16];    /* Message authentication code */
uint8_t cipher_text[12];              /* Encrypted message */
arc4random_buf(key,   32);
arc4random_buf(nonce, 24);
crypto_aead_ctx ctx;
crypto_aead_init_x(&ctx, key, nonce);
crypto_aead_write(&ctx, cipher_text, mac,
                  NULL, 0,
                  plain_text, sizeof(plain_text));
/* Wipe secrets if they are no longer needed */
crypto_wipe(plain_text, 12);
crypto_wipe(key, 32);
crypto_wipe(&ctx, sizeof(ctx));
/* Transmit cipher_text, nonce, and mac over the network,
 * store them in a file, etc.
 */

🌈 To decrypt the above 🌈

uint8_t       key        [32]; /* Same as the above        */
uint8_t       nonce      [24]; /* Same as the above        */
const uint8_t cipher_text[12]; /* Encrypted message        */
const uint8_t mac        [16]; /* Received along with text */
uint8_t       plain_text [12]; /* Secret message           */
crypto_aead_ctx ctx;
crypto_aead_init_x(&ctx, key, nonce);
if (crypto_aead_read(&ctx, plain_text, mac,
                     NULL, 0,
                     cipher_text, sizeof(plain_text))) {
        /* The message is corrupted.
         * Wipe key if it is no longer needed,
         * and abort the decryption.
         */
        crypto_wipe(key, 32);
        crypto_wipe(&ctx, sizeof(ctx));
} else {
        /* ...do something with the decrypted text here... */
        /* Finally, wipe secrets if they are no longer needed */
        crypto_wipe(plain_text, 12);
        crypto_wipe(key, 32);
        crypto_wipe(&ctx, sizeof(ctx));
}

πŸ‘€ SEE ALSO πŸ‘€

go read those too bestie, they're literally right there 🫢


πŸ“œ STANDARDS πŸ“œ

so these functions implement RFC 8439, periodt. crypto_aead_lock() and crypto_aead_init_x() use XChaCha20 instead of ChaCha20, which is the whole point ✨.

  • crypto_aead_init_djb() β€” uses a 64-bit nonce and a 64-bit counter.
  • crypto_aead_init_ietf() β€” fully compatible with the RFC. and note that XChaCha20 derives from ChaCha20 the same way XSalsa20 derives from Salsa20, and it benefits from the same security reduction (proven secure as long as ChaCha20 itself is secure) πŸ”₯.

crypto_aead_read() and crypto_aead_write() preserve the nonce and counter defined in crypto_aead_init_x(), crypto_aead_init_djb(), or crypto_aead_init_ietf(), and instead change the session key. The new session key is made from bytes [32..63] of the ChaCha20 stream used to generate the authentication key and encrypt the message. (Recall that bytes [0..31] are the authentication key, and bytes [64..] are used to encrypt the message.) πŸ‘‘


πŸ•°οΈ HISTORY πŸ•°οΈ

storytime, bestie, the lore is real 😭:

  • The crypto_lock() and crypto_unlock() functions first appeared in Monocypher 0.1.
  • crypto_lock_aead() and crypto_unlock_aead() were introduced in Monocypher 1.1.0.
  • In Monocypher 2.0.0, the underlying algorithms for these functions were changed from a custom XChaCha20/Poly1305 construction to an implementation of RFC 7539 (now RFC 8439) with XChaCha20 instead of ChaCha20.
  • The crypto_lock_encrypt() and crypto_lock_auth() functions were removed in Monocypher 2.0.0.
  • In Monocypher 4.0.0, the crypto_lock() and crypto_unlock() were removed. Functions were renamed and arguments reordered for consistency, and the incremental interface was added.

⚠️ CAVEATS ⚠️

okay real talk for a sec πŸ’€ β€” Monocypher does not perform any input validation. Any deviation from the specified input and output length ranges results in undefined behaviour. So make sure your inputs are correct, fr fr. No cap, no take-backs, just check your lengths πŸ”΄.

and that's the whole page, bestie πŸŽ€ this one came from Debian, dated March 6, 2023, and it's filed under CRYPTO_LOCK(3MONOCYPHER) β€” now go encrypt something responsibly, mwah πŸ’‹βœ¨

πŸ“¦ where this page comes from
  • nixpkgs unstable: monocypher 4.0.3
  • πŸ“œ the page's license: BSD-2-Clause OR CC0-1.0
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms