I was looking for libraries to implement an encryption system and was interested in using the NaCl: Networking and Cryptography library specifically the box function. Obviously,
crypto_box
work?box
uses a Diffie-Hellman key exchange on the two keys and hashes the result. Then it uses that as the key for secret_box
.
crypto_box
is equivalent to crypto_box_beforenm
followed by crypto_box_afternm
.
crypto_box_beforenm
is the hashed key-exchange which works as described in the Curve25519 paper, using elliptic curve Diffie-Hellman key exchange on Curve25519 hashing the result with HSalsa. This yields a 32 byte shared key.
k = Hash(Curve25519(b, A)) = Hash(Curve25519(a, B))
crypto_box_afternm
is identical to crypto_secret_box
. It takes a 24 byte nonce and a 32 byte key. It's an authenticated stream cipher using XSalsa20 for encryption and Poly1305 as MAC. The first 32 bytes of the output of XSalsa20 are used for the MAC, the rest are xor
ed into the plaintext to encrypt it.
If you take two fixed key-pairs, the result of the key exchange will always be the same.
But the symmetric part secret_box
is secure even when you use a key several times, as long as you never reuse a nonce for that key, i.e. the (key, nonce) pair must be unique.
This property is pretty much the same for all modern authenticated stream ciphers, such as AES-GCM or XSalsa20-Poly1305.
Common ways to create a unique nonce are: