2
0

ecdh.c 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /*
  2. * Copyright 2023 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #include <stdio.h>
  10. #include <string.h>
  11. #include <openssl/core_names.h>
  12. #include <openssl/evp.h>
  13. #include <openssl/err.h>
  14. /*
  15. * This is a demonstration of key exchange using ECDH.
  16. *
  17. * EC key exchange requires 2 parties (peers) to first agree on shared group
  18. * parameters (the EC curve name). Each peer then generates a public/private
  19. * key pair using the shared curve name. Each peer then gives their public key
  20. * to the other peer. A peer can then derive the same shared secret using their
  21. * private key and the other peers public key.
  22. */
  23. /* Object used to store information for a single Peer */
  24. typedef struct peer_data_st {
  25. const char *name; /* name of peer */
  26. const char *curvename; /* The shared curve name */
  27. EVP_PKEY *priv; /* private keypair */
  28. EVP_PKEY *pub; /* public key to send to other peer */
  29. unsigned char *secret; /* allocated shared secret buffer */
  30. size_t secretlen;
  31. } PEER_DATA;
  32. /*
  33. * The public key needs to be given to the other peer
  34. * The following code extracts the public key data from the private key
  35. * and then builds an EVP_KEY public key.
  36. */
  37. static int get_peer_public_key(PEER_DATA *peer, OSSL_LIB_CTX *libctx)
  38. {
  39. int ret = 0;
  40. EVP_PKEY_CTX *ctx;
  41. OSSL_PARAM params[3];
  42. unsigned char pubkeydata[256];
  43. size_t pubkeylen;
  44. /* Get the EC encoded public key data from the peers private key */
  45. if (!EVP_PKEY_get_octet_string_param(peer->priv, OSSL_PKEY_PARAM_PUB_KEY,
  46. pubkeydata, sizeof(pubkeydata),
  47. &pubkeylen))
  48. return 0;
  49. /* Create a EC public key from the public key data */
  50. ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);
  51. if (ctx == NULL)
  52. return 0;
  53. params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
  54. (char *)peer->curvename, 0);
  55. params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,
  56. pubkeydata, pubkeylen);
  57. params[2] = OSSL_PARAM_construct_end();
  58. ret = EVP_PKEY_fromdata_init(ctx) > 0
  59. && (EVP_PKEY_fromdata(ctx, &peer->pub, EVP_PKEY_PUBLIC_KEY,
  60. params) > 0);
  61. EVP_PKEY_CTX_free(ctx);
  62. return ret;
  63. }
  64. static int create_peer(PEER_DATA *peer, OSSL_LIB_CTX *libctx)
  65. {
  66. int ret = 0;
  67. EVP_PKEY_CTX *ctx = NULL;
  68. OSSL_PARAM params[2];
  69. params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,
  70. (char *)peer->curvename, 0);
  71. params[1] = OSSL_PARAM_construct_end();
  72. ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);
  73. if (ctx == NULL)
  74. return 0;
  75. if (EVP_PKEY_keygen_init(ctx) <= 0
  76. || !EVP_PKEY_CTX_set_params(ctx, params)
  77. || EVP_PKEY_generate(ctx, &peer->priv) <= 0
  78. || !get_peer_public_key(peer, libctx)) {
  79. EVP_PKEY_free(peer->priv);
  80. peer->priv = NULL;
  81. goto err;
  82. }
  83. ret = 1;
  84. err:
  85. EVP_PKEY_CTX_free(ctx);
  86. return ret;
  87. }
  88. static void destroy_peer(PEER_DATA *peer)
  89. {
  90. EVP_PKEY_free(peer->priv);
  91. EVP_PKEY_free(peer->pub);
  92. }
  93. static int generate_secret(PEER_DATA *peerA, EVP_PKEY *peerBpub,
  94. OSSL_LIB_CTX *libctx)
  95. {
  96. unsigned char *secret = NULL;
  97. size_t secretlen = 0;
  98. EVP_PKEY_CTX *derivectx;
  99. /* Create an EVP_PKEY_CTX that contains peerA's private key */
  100. derivectx = EVP_PKEY_CTX_new_from_pkey(libctx, peerA->priv, NULL);
  101. if (derivectx == NULL)
  102. return 0;
  103. if (EVP_PKEY_derive_init(derivectx) <= 0)
  104. goto cleanup;
  105. /* Set up peerB's public key */
  106. if (EVP_PKEY_derive_set_peer(derivectx, peerBpub) <= 0)
  107. goto cleanup;
  108. /*
  109. * For backwards compatibility purposes the OpenSSL ECDH provider supports
  110. * optionally using a X963KDF to expand the secret data. This can be done
  111. * with code similar to the following.
  112. *
  113. * OSSL_PARAM params[5];
  114. * size_t outlen = 128;
  115. * unsigned char ukm[] = { 1, 2, 3, 4 };
  116. * params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE,
  117. * "X963KDF", 0);
  118. * params[1] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST,
  119. * "SHA256", 0);
  120. * params[2] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN,
  121. * &outlen);
  122. * params[3] = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM,
  123. * ukm, sizeof(ukm));
  124. * params[4] = OSSL_PARAM_construct_end();
  125. * if (!EVP_PKEY_CTX_set_params(derivectx, params))
  126. * goto cleanup;
  127. *
  128. * Note: After the secret is generated below, the peer could alternatively
  129. * pass the secret to a KDF to derive additional key data from the secret.
  130. * See demos/kdf/hkdf.c for an example (where ikm is the secret key)
  131. */
  132. /* Calculate the size of the secret and allocate space */
  133. if (EVP_PKEY_derive(derivectx, NULL, &secretlen) <= 0)
  134. goto cleanup;
  135. secret = (unsigned char *)OPENSSL_malloc(secretlen);
  136. if (secret == NULL)
  137. goto cleanup;
  138. /*
  139. * Derive the shared secret. In this example 32 bytes are generated.
  140. * For EC curves the secret size is related to the degree of the curve
  141. * which is 256 bits for P-256.
  142. */
  143. if (EVP_PKEY_derive(derivectx, secret, &secretlen) <= 0)
  144. goto cleanup;
  145. peerA->secret = secret;
  146. peerA->secretlen = secretlen;
  147. printf("Shared secret (%s):\n", peerA->name);
  148. BIO_dump_indent_fp(stdout, peerA->secret, peerA->secretlen, 2);
  149. putchar('\n');
  150. return 1;
  151. cleanup:
  152. OPENSSL_free(secret);
  153. EVP_PKEY_CTX_free(derivectx);
  154. return 0;
  155. }
  156. int main(void)
  157. {
  158. int ret = EXIT_FAILURE;
  159. /* Initialise the 2 peers that will share a secret */
  160. PEER_DATA peer1 = {"peer 1", "P-256"};
  161. PEER_DATA peer2 = {"peer 2", "P-256"};
  162. /*
  163. * Setting libctx to NULL uses the default library context
  164. * Use OSSL_LIB_CTX_new() to create a non default library context
  165. */
  166. OSSL_LIB_CTX *libctx = NULL;
  167. /* Each peer creates a (Ephemeral) keypair */
  168. if (!create_peer(&peer1, libctx)
  169. || !create_peer(&peer2, libctx)) {
  170. fprintf(stderr, "Create peer failed\n");
  171. goto cleanup;
  172. }
  173. /*
  174. * Each peer uses its private key and the other peers public key to
  175. * derive a shared secret
  176. */
  177. if (!generate_secret(&peer1, peer2.pub, libctx)
  178. || !generate_secret(&peer2, peer1.pub, libctx)) {
  179. fprintf(stderr, "Generate secrets failed\n");
  180. goto cleanup;
  181. }
  182. /* For illustrative purposes demonstrate that the derived secrets are equal */
  183. if (peer1.secretlen != peer2.secretlen
  184. || CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secretlen) != 0) {
  185. fprintf(stderr, "Derived secrets do not match\n");
  186. goto cleanup;
  187. } else {
  188. fprintf(stdout, "Derived secrets match\n");
  189. }
  190. ret = EXIT_SUCCESS;
  191. cleanup:
  192. if (ret != EXIT_SUCCESS)
  193. ERR_print_errors_fp(stderr);
  194. destroy_peer(&peer2);
  195. destroy_peer(&peer1);
  196. return ret;
  197. }