Path: blob/main/crypto/openssl/demos/keyexch/ecdh.c
34869 views
/*1* Copyright 2023-2024 The OpenSSL Project Authors. All Rights Reserved.2*3* Licensed under the Apache License 2.0 (the "License"). You may not use4* this file except in compliance with the License. You can obtain a copy5* in the file LICENSE in the source distribution or at6* https://www.openssl.org/source/license.html7*/89#include <stdio.h>10#include <string.h>11#include <openssl/core_names.h>12#include <openssl/evp.h>13#include <openssl/err.h>1415/*16* This is a demonstration of key exchange using ECDH.17*18* EC key exchange requires 2 parties (peers) to first agree on shared group19* parameters (the EC curve name). Each peer then generates a public/private20* key pair using the shared curve name. Each peer then gives their public key21* to the other peer. A peer can then derive the same shared secret using their22* private key and the other peers public key.23*/2425/* Object used to store information for a single Peer */26typedef struct peer_data_st {27const char *name; /* name of peer */28const char *curvename; /* The shared curve name */29EVP_PKEY *priv; /* private keypair */30EVP_PKEY *pub; /* public key to send to other peer */31unsigned char *secret; /* allocated shared secret buffer */32size_t secretlen;33} PEER_DATA;3435/*36* The public key needs to be given to the other peer37* The following code extracts the public key data from the private key38* and then builds an EVP_KEY public key.39*/40static int get_peer_public_key(PEER_DATA *peer, OSSL_LIB_CTX *libctx)41{42int ret = 0;43EVP_PKEY_CTX *ctx;44OSSL_PARAM params[3];45unsigned char pubkeydata[256];46size_t pubkeylen;4748/* Get the EC encoded public key data from the peers private key */49if (!EVP_PKEY_get_octet_string_param(peer->priv, OSSL_PKEY_PARAM_PUB_KEY,50pubkeydata, sizeof(pubkeydata),51&pubkeylen))52return 0;5354/* Create a EC public key from the public key data */55ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);56if (ctx == NULL)57return 0;58params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,59(char *)peer->curvename, 0);60params[1] = OSSL_PARAM_construct_octet_string(OSSL_PKEY_PARAM_PUB_KEY,61pubkeydata, pubkeylen);62params[2] = OSSL_PARAM_construct_end();63ret = EVP_PKEY_fromdata_init(ctx) > 064&& (EVP_PKEY_fromdata(ctx, &peer->pub, EVP_PKEY_PUBLIC_KEY,65params) > 0);66EVP_PKEY_CTX_free(ctx);67return ret;68}6970static int create_peer(PEER_DATA *peer, OSSL_LIB_CTX *libctx)71{72int ret = 0;73EVP_PKEY_CTX *ctx = NULL;74OSSL_PARAM params[2];7576params[0] = OSSL_PARAM_construct_utf8_string(OSSL_PKEY_PARAM_GROUP_NAME,77(char *)peer->curvename, 0);78params[1] = OSSL_PARAM_construct_end();7980ctx = EVP_PKEY_CTX_new_from_name(libctx, "EC", NULL);81if (ctx == NULL)82return 0;8384if (EVP_PKEY_keygen_init(ctx) <= 085|| !EVP_PKEY_CTX_set_params(ctx, params)86|| EVP_PKEY_generate(ctx, &peer->priv) <= 087|| !get_peer_public_key(peer, libctx)) {88EVP_PKEY_free(peer->priv);89peer->priv = NULL;90goto err;91}92ret = 1;93err:94EVP_PKEY_CTX_free(ctx);95return ret;96}9798static void destroy_peer(PEER_DATA *peer)99{100EVP_PKEY_free(peer->priv);101EVP_PKEY_free(peer->pub);102}103104static int generate_secret(PEER_DATA *peerA, EVP_PKEY *peerBpub,105OSSL_LIB_CTX *libctx)106{107unsigned char *secret = NULL;108size_t secretlen = 0;109EVP_PKEY_CTX *derivectx;110111/* Create an EVP_PKEY_CTX that contains peerA's private key */112derivectx = EVP_PKEY_CTX_new_from_pkey(libctx, peerA->priv, NULL);113if (derivectx == NULL)114return 0;115116if (EVP_PKEY_derive_init(derivectx) <= 0)117goto cleanup;118/* Set up peerB's public key */119if (EVP_PKEY_derive_set_peer(derivectx, peerBpub) <= 0)120goto cleanup;121122/*123* For backwards compatibility purposes the OpenSSL ECDH provider supports124* optionally using a X963KDF to expand the secret data. This can be done125* with code similar to the following.126*127* OSSL_PARAM params[5];128* size_t outlen = 128;129* unsigned char ukm[] = { 1, 2, 3, 4 };130* params[0] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_TYPE,131* "X963KDF", 0);132* params[1] = OSSL_PARAM_construct_utf8_string(OSSL_EXCHANGE_PARAM_KDF_DIGEST,133* "SHA256", 0);134* params[2] = OSSL_PARAM_construct_size_t(OSSL_EXCHANGE_PARAM_KDF_OUTLEN,135* &outlen);136* params[3] = OSSL_PARAM_construct_octet_string(OSSL_EXCHANGE_PARAM_KDF_UKM,137* ukm, sizeof(ukm));138* params[4] = OSSL_PARAM_construct_end();139* if (!EVP_PKEY_CTX_set_params(derivectx, params))140* goto cleanup;141*142* Note: After the secret is generated below, the peer could alternatively143* pass the secret to a KDF to derive additional key data from the secret.144* See demos/kdf/hkdf.c for an example (where ikm is the secret key)145*/146147/* Calculate the size of the secret and allocate space */148if (EVP_PKEY_derive(derivectx, NULL, &secretlen) <= 0)149goto cleanup;150secret = (unsigned char *)OPENSSL_malloc(secretlen);151if (secret == NULL)152goto cleanup;153154/*155* Derive the shared secret. In this example 32 bytes are generated.156* For EC curves the secret size is related to the degree of the curve157* which is 256 bits for P-256.158*/159if (EVP_PKEY_derive(derivectx, secret, &secretlen) <= 0)160goto cleanup;161peerA->secret = secret;162peerA->secretlen = secretlen;163164printf("Shared secret (%s):\n", peerA->name);165BIO_dump_indent_fp(stdout, peerA->secret, peerA->secretlen, 2);166putchar('\n');167168return 1;169cleanup:170OPENSSL_free(secret);171EVP_PKEY_CTX_free(derivectx);172return 0;173}174175int main(void)176{177int ret = EXIT_FAILURE;178/* Initialise the 2 peers that will share a secret */179PEER_DATA peer1 = {"peer 1", "P-256"};180PEER_DATA peer2 = {"peer 2", "P-256"};181/*182* Setting libctx to NULL uses the default library context183* Use OSSL_LIB_CTX_new() to create a non default library context184*/185OSSL_LIB_CTX *libctx = NULL;186187/* Each peer creates a (Ephemeral) keypair */188if (!create_peer(&peer1, libctx)189|| !create_peer(&peer2, libctx)) {190fprintf(stderr, "Create peer failed\n");191goto cleanup;192}193194/*195* Each peer uses its private key and the other peers public key to196* derive a shared secret197*/198if (!generate_secret(&peer1, peer2.pub, libctx)199|| !generate_secret(&peer2, peer1.pub, libctx)) {200fprintf(stderr, "Generate secrets failed\n");201goto cleanup;202}203204/* For illustrative purposes demonstrate that the derived secrets are equal */205if (peer1.secretlen != peer2.secretlen206|| CRYPTO_memcmp(peer1.secret, peer2.secret, peer1.secretlen) != 0) {207fprintf(stderr, "Derived secrets do not match\n");208goto cleanup;209} else {210fprintf(stdout, "Derived secrets match\n");211}212213ret = EXIT_SUCCESS;214cleanup:215if (ret != EXIT_SUCCESS)216ERR_print_errors_fp(stderr);217destroy_peer(&peer2);218destroy_peer(&peer1);219return ret;220}221222223