jedisct1 / libsodium

A modern, portable, easy to use crypto library.
https://libsodium.org
Other
12.26k stars 1.75k forks source link

Ciphertext padding length in crypto_secretstream_xchacha20poly1305_push #976

Closed ionspin closed 4 years ago

ionspin commented 4 years ago

I am implementing a kotlin version of some of the primitives found in libsodium for fun and learning purposes. I am a bit confused about the ciphertext padding length in crypto_secretstream_xchacha20poly1305_push and _pull.

I presumed that like additionalData pad, the length should make the resulting array be divisible with 16, but for ciphertext data, it seems that the calculated pad length is not divisible by 16.

Code that calculates the padding length that is sent to poly1305 is here

crypto_onetimeauth_poly1305_update(&poly1305_state, _pad0, (0x10 - (sizeof block) + mlen) & 0xf);

As an example when trying to apply this to a message of length 100, the resulting pad length is 4, which doesn't produce an array of bytes divisible by 16.

Is this expected behavior?

jedisct1 commented 4 years ago

You're right, it should be (0x10 - (sizeof block + mlen)) & 0xf to match the description and keep input blocks aligned.

This is too late to change this in libsodium, but if compatibility is not an issue, this is probably something you should do in your implementation !