Skip to content

Secretbox

XSalsa20-Poly1305 symmetric authenticated encryption with a shared secret key. Both combined (seal/open) and detached (sealDetached/openDetached) forms are available. Combined: 16-byte MAC prepended to ciphertext. Detached: MAC and ciphertext returned separately as { cipher, mac }.

Secretbox . keygen ( )  -> buffer

Generates a random 32-byte secretbox key via libsodium’s CSPRNG.

Returns

buffer
Secretbox . 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 key.

Returns

buffer
Secretbox . seal ( message key nonce )  -> buffer

Encrypts message with key (32 bytes) and nonce (24 bytes). Returns a combined buffer: [mac (16 B)][ciphertext]. Errors if encryption fails.

Parameters

message: buffer
key: buffer
nonce: buffer

Returns

buffer
Secretbox . open ( ciphertext key nonce )  -> buffer

Decrypts a combined ciphertext (produced by seal) with key and nonce. Returns the plaintext. Errors if the MAC does not verify.

Parameters

ciphertext: buffer
key: buffer
nonce: buffer

Returns

buffer
Secretbox . sealDetached ( message key nonce )  -> SealResult

Encrypts message with key (32 bytes) and nonce (24 bytes), returning MAC and ciphertext separately. Ciphertext is the same length as the message; result is { cipher, mac }. Errors if encryption fails.

Parameters

message: buffer
key: buffer
nonce: buffer

Returns

SealResult
Secretbox . openDetached ( cipher mac key nonce )  -> buffer

Decrypts cipher using its detached mac, key (32 bytes), and nonce (24 bytes). Returns the plaintext. Errors if the MAC does not verify.

Parameters

cipher: buffer
mac: buffer
key: buffer
nonce: buffer

Returns

buffer