Skip to content

Box

X25519 + XSalsa20-Poly1305 public-key authenticated encryption. Encrypts from sender secret key to recipient public key; only the recipient can decrypt. Both parties must know each other’s public key; call precompute once per recipient to derive a shared key and avoid repeated Diffie-Hellman for multiple messages.

Box . keypair ( )  -> Keypair

Generates a random X25519 keypair; public key is safe to share, secret key must be kept private. The secret key is 32 bytes.

Returns

Keypair
Box . nonce ( )  -> buffer

Generates a random 24-byte nonce via libsodium’s CSPRNG. Generate a fresh nonce for every message - never reuse a nonce with the same keypair.

Returns

buffer
Box . seal ( message recipientPublicKey senderSecretKey nonce )  -> buffer

Encrypts message from senderSecretKey to recipientPublicKey using nonce (24 bytes). Returns a combined buffer: [mac (16 B)][ciphertext].

Parameters

message: buffer
recipientPublicKey: buffer
senderSecretKey: buffer
nonce: buffer

Returns

buffer
Box . open ( ciphertext senderPublicKey recipientSecretKey nonce )  -> buffer

Decrypts a combined ciphertext (from seal) using senderPublicKey, recipientSecretKey, and nonce. Errors if the MAC does not verify.

Parameters

ciphertext: buffer
senderPublicKey: buffer
recipientSecretKey: buffer
nonce: buffer

Returns

buffer
Box . sealDetached ( message recipientPublicKey senderSecretKey nonce )  -> SealResult

Encrypts message from senderSecretKey to recipientPublicKey, returning MAC and ciphertext separately. Ciphertext is the same length as the message; MAC and ciphertext are returned as { cipher, mac }.

Parameters

message: buffer
recipientPublicKey: buffer
senderSecretKey: buffer
nonce: buffer

Returns

SealResult
Box . openDetached ( cipher mac senderPublicKey recipientSecretKey nonce )  -> buffer

Decrypts cipher using its detached mac, senderPublicKey, recipientSecretKey, and nonce. Errors if the MAC does not verify.

Parameters

cipher: buffer
mac: buffer
senderPublicKey: buffer
recipientSecretKey: buffer
nonce: buffer

Returns

buffer
Box . precompute ( recipientPublicKey senderSecretKey )  -> buffer

Computes a 32-byte shared key from recipientPublicKey and senderSecretKey via X25519 Diffie-Hellman. Pass the result to sealAfterPrecompute/openAfterPrecompute to avoid repeating the DH per message.

Parameters

recipientPublicKey: buffer
senderSecretKey: buffer

Returns

buffer
Box . sealAfterPrecompute ( message sharedKey nonce )  -> buffer

Encrypts message using a precomputed sharedKey (from precompute) and nonce. Returns a combined buffer: [mac (16 B)][ciphertext].

Parameters

message: buffer
sharedKey: buffer
nonce: buffer

Returns

buffer
Box . openAfterPrecompute ( ciphertext sharedKey nonce )  -> buffer

Decrypts a combined ciphertext (from sealAfterPrecompute) using a precomputed sharedKey and nonce. Errors if the MAC does not verify.

Parameters

ciphertext: buffer
sharedKey: buffer
nonce: buffer

Returns

buffer