dchest / tweetnacl-js

Port of TweetNaCl cryptographic library to JavaScript
https://tweetnacl.js.org
The Unlicense
1.75k stars 292 forks source link

Is it safe to use sha512(input + static salt) to generate the nonce? #207

Closed chmac closed 3 years ago

chmac commented 3 years ago

Firstly, thanks for this repo. It has made secure crypto super accessible in javascript.

I'm building git-remote-encrypted, an encrypted git remote helper, for javascript (via isomorphic-git) and as a git helper. I'd like the output of the encryption to be deterministic, so that if 2 users have the same keys, and encrypt the same repo, they will get the same result.

My strategy is to use 1 key and one "salt". To encrypt a git object, I use the object ID (which is an sha1 of its contents), combine that with the salt, and then sha512 the result. Or in other words:

sha512(sha1oid + salt).substr(nonce_length)

This results in a "unique" nonce per encryption. However, I wonder if this is really secure. I believe that using a predictable, deterministic manner of generating nonces might be weak. I'm unsure as my cryptofu is extremely limited.

If you feel this question would be better asked on the crypto stackexchange, feel free to close without comment and I'll post there instead.

dchest commented 3 years ago

Deterministic nonce generation from content (or its cryptographic hash) is indeed safe for XSalsa20 up to a certain large limit of the number of encrypted messages (2^192 nonce space), so your idea is fine in principle. However, since SHA-1 is no longer collision-resistant, it would be possible to produce two different messages with the same nonce, breaking encryption.

I believe that using a predictable, deterministic manner of generating nonces might be weak.

Nonces for Salsa20 or AES-CTR/GCM, as opposed to IVs for AES-CBC, do not need to be unpredictable or random. The only requirement is that they must be different for different messages for the same key.

(PS Yes, it's better to ask such questions on crypto stackexchange :)

chmac commented 3 years ago

Thanks for the super quick reply, I appreciate it.

The sha1 part comes from git itself, so that's outside of my control. If there are 2 values with the same sha1, then git will probably get confused as to which is which!

I'll close this now as you've graciously answered the question and I'll put any further questions on crypto stackexchange. 👍