Saturday, October 30, 2021

[SOLVED] Check whether OpenSSL supports certain curve via header/define in CMake

Issue

I need to check whether OpenSSL supports certain Elliptic Curve(s) via CMake. While cipher and hash availability may be checked via existence of functions from openssl/evp.h, like check_cxx_symbol_exists("EVP_md4", openssl/evp.h, _openssl_has_md4), I don't see a way to do the same for curves.

Do I miss something, or there is no better way than checking the output of openssl ecparam list_curves?

Update: Since my code doesn't require openssl executable, it would be quite desirable to avoid dependency on it for building.


Solution

This code (mostly taken from openssl) lists the available ECs:

#include <stdio.h>
#include <openssl/ec.h>
#include <openssl/objects.h>

int
main ()
{
  int ret = 1;
  EC_builtin_curve *curves = NULL;
  size_t n, crv_len = EC_get_builtin_curves (NULL, 0);

  curves = OPENSSL_malloc((int)sizeof(*curves) * crv_len);
  if (curves == NULL)
    goto end;

  if (!EC_get_builtin_curves (curves, crv_len))
    goto memfree;

  for (n = 0; n < crv_len; n++)
    {
      const char *comment = curves[n].comment;
      const char *sname = OBJ_nid2sn (curves[n].nid);

      if (comment == NULL)
        comment = "CURVE DESCRIPTION NOT AVAILABLE";
      if (sname == NULL)
        sname = "";

      printf ("%s\t%s\n", sname, comment);
    }
  ret = 0;

memfree:
  OPENSSL_free (curves);

end:
  return ret;
}

Output on my laptop:

$ gcc -Wall -L /usr/lib64 -lcrypto -lssl eclist.c -o eclist
$ ./eclist
secp224r1       NIST/SECG curve over a 224 bit prime field
secp256k1       SECG curve over a 256 bit prime field
secp384r1       NIST/SECG curve over a 384 bit prime field
secp521r1       NIST/SECG curve over a 521 bit prime field
prime256v1      X9.62/SECG curve over a 256 bit prime field

The openssl binary gives me the same output:

$ openssl ecparam -list_curves
  secp224r1 : NIST/SECG curve over a 224 bit prime field
  secp256k1 : SECG curve over a 256 bit prime field
  secp384r1 : NIST/SECG curve over a 384 bit prime field
  secp521r1 : NIST/SECG curve over a 521 bit prime field
  prime256v1: X9.62/SECG curve over a 256 bit prime field

Of course printing the values this way may not be very usefull, but the code can be hopefully the base for a test CMake.



Answered By - Davide Madrisan