'C++ generate new EC_KEY using OpenSSL 1.1.1n

I'm very new to this OpenSSL stuff and trying to learn my way through it. I want to generate an ec key but its keep failing to generate. I'm currently using OpenSSL 1.1.1n and here's a snippet based on understaning of EC_Key through documentation and from other people's example online:

EC_KEY* key = EC_KEY_new_by_curve_name(NID_secp521r1);
if (!key)
{
    ERROR
}

EC_GROUP* ecgroup = EC_GROUP_new_by_curve_name(NID_secp521r1);
if (ecgroup)
{
    printf("ECGROUP IS NOT NULL!\n");
    if (EC_KEY_set_group(key, ecgroup) != 1)
    {
        ERROR
    }
}

if (EC_KEY_generate_key(key) != 1) //<-- fails at this function
{
    ERROR
}

Maybe this piece of code is from an older version of OpenSSL but I don't see that function being mentioned in a change log. Any help would be really appreciated! Thanks in advance!

Edit:

Thanks for Jakob's answer I was able to get some more information about the failure by using ERR_get_error() function. The error I see now is error:2406C06E:random number generator:RAND_DRBG_instantiate:error retrieving entropy



Solution 1:[1]

Answering myself in case someone is having this same issue.

I was able to get around this problem by building OpenSSl with no-shared flag. I'm not sure how that is affecting the lib in getting an entropy but that's the parameter that made the EC_KEY_generate_key() work.

Here's my working configuration command: perl Configure no-shared VC-WIN32

Solution 2:[2]

The manual states:

EC_KEY_generate_key() generates a new public and private key for the supplied eckey object. eckey must have an EC_GROUP object associated with it before calling this function. [...]

Did you associate an EC_GROUP with the key before calling the function? There is a function called EC_KEY_set_group() which can be used to add a group object. Such an object can be created with the EC_GROUP_new().

By the way is there a reason, why you are still using OpenSSL 1.1.1. I would recommend using the latest version of the library OpenSSL 3.0. Even if you only want to learn stuff, it is probably more useful, if you immediately learn the newer version.

Edit
I do not know, what is behind your ERROR macro, but it might be a good idea to learn the OpenSSL error handling system. There are functions like ERR_print_errors() that maybe could have given you a hint about what was going wrong.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 M. Ather Khan
Solution 2