crypto_key_exchange,
crypto_key_exchange_public_key —
Elliptic Curve Diffie-Hellman key exchange
#include
<monocypher.h>
int
crypto_key_exchange(
uint8_t
shared_key[32],
const uint8_t
your_secret_key[32],
const uint8_t
their_public_key[32]);
void
crypto_key_exchange_public_key(
uint8_t
your_public_key[32],
const uint8_t
your_secret_key[32]);
crypto_key_exchange() computes a shared key with
your secret key and their public key.
crypto_key_exchange_public_key() deterministically
computes the public key from a random secret key.
The arguments are:
-
-
- shared_key
- The shared secret, known only to those who know a relevant
secret key (yours or theirs). It is cryptographically random, and suitable
for use with the
crypto_lock(3monocypher)
family of functions.
-
-
- your_secret_key
- A 32-byte random number, known only to you. See
intro(3monocypher) for
advice about generating random bytes (use the operating system's random
number generator). Do not use the same private key for both key exchanges
and signatures. The public keys are different, and revealing both may leak
information.
-
-
- their_public_key
- The public key of the other party.
-
-
- your_public_key
- Your public key, generated from
your_secret_key with
crypto_key_exchange_public_key().
Some public keys force the shared key to a known constant.
crypto_key_exchange() returns -1 if it detects
such a public key, otherwise it returns 0. This never happens with legitimate
public keys, but if the ones you process are not known to be trustworthy,
check the return value.
crypto_key_exchange_public_key() returns nothing.
Generate a public key from a randomly generated secret key:
const uint8_t sk[32]; /* Random secret key */
uint8_t pk[32]; /* Public key */
crypto_key_exchange_public_key(pk, sk);
/* Wipe secrets if they are no longer needed */
crypto_wipe(sk, 32);
Generate a shared, symmetric key with your secret key and their public key. (The
other party will generate the same shared key with your public key and their
secret key.)
const uint8_t their_pk [32]; /* Their public key */
const uint8_t your_sk [32]; /* Your secret key */
uint8_t shared_key[32]; /* Shared session key */
if (crypto_key_exchange(shared_key, your_sk, their_pk) != 0) {
/* Their public key is malicious. */
/* The exchange must be aborted. */
}
/* Wipe secrets if they are no longer needed */
crypto_wipe(your_sk, 32);
crypto_lock(3monocypher),
intro(3monocypher)
These functions implement X25519, described in RFC 7748.
crypto_key_exchange() uses HChacha20 as well.
If either of the long term secret keys leaks, it may compromise
all past messages. This can be avoided by using
protocols that provide forward secrecy, such as the X3DH key agreement
protocol.
crypto_key_exchange_public_key() is an alias to
crypto_x25519_public_key(3monocypher).