Quantcast
Channel: Active questions tagged gcc - Stack Overflow
Viewing all articles
Browse latest Browse all 22079

The const conundrum in OpenSSL

$
0
0

In OpenSSL, some functions require the use of const but then down the road others require me to not use const for the same variable. An example is when I create a new BIGNUM I need to use const but then to free it I cannot have const.

Is there a trick to solve this? What would be the proper why to get rid of the compiler warnings?


Function signatures:

const BIGNUM *EC_KEY_get0_private_key(const EC_KEY *key);
void BN_free(BIGNUM *a);

Offending code:

EC_KEY *ec_key = ...;
/*const*/ BIGNUM *bignum = NULL;
bignum = EC_KEY_get0_private_key(ec_key);
BN_free(bignum);

Compiler warnings:

------------Without const in bignum------------:
warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
  bignum = EC_KEY_get0_private_key(ec_key);
     ^

------------With const in bignum------------:
warning: passing argument 1 of ‘BN_free’ discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
  BN_free(bignum);
          ^
In file included from /usr/include/openssl/asn1.h:74:0,
                 from /usr/include/openssl/objects.h:965,
                 from /usr/include/openssl/evp.h:94,
                 from ecdh.c:5:
/usr/include/openssl/bn.h:493:6: note: expected ‘BIGNUM * {aka struct bignum_st *}’ but argument is of type ‘const BIGNUM * {aka const struct bignum_st *}’
 void BN_free(BIGNUM *a);

Edit to add working example:

#include <openssl/evp.h>
#include <openssl/ec.h>
#include <openssl/bn.h>

int main()
{
    EC_KEY *ec_key = NULL;
    const BIGNUM *bignum = NULL;

    ec_key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    bignum = EC_KEY_get0_private_key(ec_key);

    //BN_free(bignum);    // unnecessary
    EC_KEY_free(ec_key);
    return 0;
}
//$ gcc -g -Wall -Wextra -o leak_ecdh leak_ecdh.c -lcrypto && valgrind --leak-check=yes ./leak_ecdh
//==26202== HEAP SUMMARY:
//==26202==     in use at exit: 0 bytes in 0 blocks
//==26202==   total heap usage: 104 allocs, 104 frees, 4,220 bytes allocated
//==26202== 
//==26202== All heap blocks were freed -- no leaks are possible

Viewing all articles
Browse latest Browse all 22079

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>