jedisct1 / libsodium

A modern, portable, easy to use crypto library.

Home Page:https://libsodium.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

is the constant crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX wrong?

ivmaykov opened this issue · comments

Does the constant crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX (defined at https://github.com/jedisct1/libsodium/blob/master/src/libsodium/include/sodium/crypto_aead_xchacha20poly1305.h#L30-L31) have the wrong value? The IETF variant of XChaCha20-Poly1305 is based on the IETF variant of ChaCha20-Poly1305, which has a 4-byte counter. Shouldn't crypto_aead_xchacha20poly1305_ietf_MESSAGEBYTES_MAX == crypto_aead_chacha20poly1305_ietf_MESSAGEBYTES_MAX?

If not, I'd love to know why not / how the counter wraparound issue is avoided.

The constant looks correct.

ChaCha has 16 bytes to share between the nonce and the counter.

For the needs of TLS, the IETF version uses 12 bytes for the nonce, 4 for the counter:

NNNNNNNNNNNNCCCC

The original version uses 8 bytes for the nonce, 8 for the counter.

NNNNNNNNCCCCCCCC

Now, XChaCha uses a 24 byte nonce. 16 bytes of it are going to be the sub-key, and there are 8 bytes left for the actual sub-nonce. So we have 8 bytes left for the counter.

nnnnnnnnCCCCCCCC

If an implementation only supports 4 bytes counters and requires 12 bytes for the nonce, it's still possible to build XChaCha in a compatible way until 2^32 blocks:

nnnnnnnn0000CCCC

32 bits would always be zero, so usage would be limited to the IETF limits. That limit would be very artificial.
But if you need to reuse a library that only supports 4 byte counters, and implement XChaCha by only adding HChaCha, you will indeed have that limit.

libsodium supports 8 bytes counters so doesn't have that limit. Internally, it's called crypto_stream_chacha20_ietf_ext, as the authenticator is computed as with ChaCha20-iETF, but we allow the counter to be 8 bytes.

Hmm I see. So it sounds like for XChaCha20-Poly1305, there is effectively no difference between the IETF and non-IETF variants (or maybe another way to think about it is, there is no such thing as non-IETF XChaCha20-Poly1305?), since both of them use 8 bytes of nonce and 8 bytes of counter after the HChaCha20 step?

Yes, even the libsodium crypto_aead API has only one version.

Thank you for clearing it up for me!