dchest / tweetnacl-js

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

Box keypair from seed? #216

Closed taoeffect closed 3 years ago

taoeffect commented 3 years ago

Is there any way to use a seed to generate the box keypair?

nacl.box.keyPair has only .fromSecretKey, not .fromSeed, and trying to put a secretKey that was generated from nacl.sign.keyPair.fromSeed doesn't work.

dchest commented 3 years ago

These APIs are indeed confusing, but basically what sign.keyPair.fromSeed does is it allows you to replace nacl's internal randombytes(32) with your own 32 bytes, which it then uses for the secret key and computes the corresponding public key:

Screen Shot 2021-06-07 at 07 42 46

The problem with the signing secret key (due to NaCl design) is that it contains both this 32-byte seed and also 32-byte public key concatenated with it (can't see it in the screenshot). What sign.keyPair.fromSecretKey does is that it takes these 64 bytes and just extracts the public key from it, creating a suitable JS object.

box.keyPair doesn't have .fromSeed because .fromSecretKey already serves the same purpose: box's secret key is just 32 random bytes. That is, .fromSeed would be the same as .fromSecretKey.

Screen Shot 2021-06-07 at 07 48 21

To summarize, if you need to get a key pair from your own 32 random or derived bytes, use: nacl.box.fromSecretKey and nacl.sign.fromSeed. If you need to get the original key pair from the secret key (32 bytes for box and 64 bytes for sign), use nacl.box.fromSecretKey and nacl.sign.fromSecretKey.

Note that box (x25519) and sign (ed25519) use different curve representations, so their keys are not compatible with each other. You can however re-use a sign key pair for box if you convert it with https://github.com/dchest/ed2curve-js.

taoeffect commented 3 years ago

Ah, ok, thank you @dchest! That's very clear and very helpful. Closing this issue then. 😄