ektrah / nsec

A modern and easy-to-use cryptographic library for .NET 8+ based on libsodium
https://nsec.rocks
MIT License
374 stars 52 forks source link

Clarify security issues when using random nonces #33

Closed thedmi closed 4 years ago

thedmi commented 4 years ago

In the API documentation, section AEAD -> encrypt there is a hint about using random values as nonce:

To prevent nonce reuse when encrypting multiple plaintexts with the same key, it is recommended to increment the previous nonce; a randomly generated nonce is not suitable.

This statement surprised me, and I'm unable to find sources that support the claim that random nonces are insecure. I was under the impression that random nonces are secure if a cryptographically secure random number generator is used.

Could you clarify why (or in which cases) random nonces are insecure?

ektrah commented 4 years ago

Putting a complex topic like nonce generation in a single sentence is always challenging...

AEAD algorithms like AES256-GCM and ChaCha20-Poly1305 fail catastrophically when a nonce is repeated even once. If you generate nonces randomly, there is a non-zero chance that a nonce will be repeated. The probability depends on the length and number of nonces generated. Due to the birthday paradox, it can be surprisingly high.

So the simplest recommendation is: Don't generate nonces randomly. But, of course, you can do a security analysis and see if the probability is an acceptable risk in your use case.

Another option is to look into XChaCha20-Poly1305, which is designed specifically with randomly generated nonces in mind. It uses 192-bit nonces instead of the default 96-bit nonces used by AES256-GCM and ChaCha20-Poly1305. (See the Motivation section for more details.) NSec doesn't include this algorithm at this time, but I guess I'll have to update the quoted documentation once it does.

Does that answer your question?

thedmi commented 4 years ago

Thanks a lot for the clarification, this answers my question. For me this means it's important to know how often a re-keying is necessary to achieve the desired nonce reuse probability. Maintaining nonce counter state is difficult in the specific scenario that I have.

Thanks again, and thanks a lot for your efforts with NSec!

ektrah commented 4 years ago

Have a look at Section 3 of RFC 5116; it provides some considerations for nonce generation in different ways. Maybe your use case can benefit from following one of these.