How to calculate public key for TLS key exchange using OpenSSL functions?

356 views Asked by At

I'm learning TLS 1.3 scheme and trying to implement basic handshake steps in C++ without using ready wrappers from OpenSSL such as SSL_accept or SSL_do_handshake. The project already uses OpenSSL for common crypto operations, so I would like not to link it with any other crypto libraries where the x25519 calculation is more obvious than in OpenSSL. So...

there are two buffers:

unsigned char private_key[32];
RAND_bytes(private_key, 32);

unsigned char public_key[32];
memset(public_key, 0, 32);

Which method(s) of OpenSSL should I use to fill public_key buffer with bytes computed from private_key using x25519 algo (copying and allocating as less as possible)?

1

There are 1 answers

0
Matt Caswell On BEST ANSWER

Create an EVP_PKEY object using the function EVP_PKEY_new_raw_private_key as described here:

https://www.openssl.org/docs/man1.1.1/man3/EVP_PKEY_new_raw_private_key.html

    EVP_PKEY key = EVP_PKEY_new_raw_private_key(EVP_PKEY_X25519, NULL, private_key, sizeof(private_key));
    if (key == NULL)
        /* Error */;

You can then obtain the public key bytes using the function EVP_PKEY_get_raw_public_key as described on the same page as above:

    size_t publen = sizeof(public_key);
    if (!EVP_PKEY_get_raw_public_key(key, public_key, &publen))
        /* Error */;