c - OpenSSL i2o_ECPublicKey not working -


i have code:

#include <stdio.h> #include <openssl/sha.h> #include <openssl/ssl.h>  int main(){     printf("openssl version: %s\n",openssl_version_text);     ec_key * key = ec_key_new_by_curve_name(nid_secp256k1);     if(!ec_key_generate_key(key)){         printf("generate key fail\n");          return 1;     }     u_int8_t pubsize = i2o_ecpublickey(key, null);     if(!pubsize){         printf("pub key data zero\n");          return 1;     }     u_int8_t * pubkey = malloc(pubsize);     if(i2o_ecpublickey(key, &pubkey) != pubsize){         printf("pub key data fail\n");          return 1;     }     u_int8_t * hash = malloc(sha256_digest_length);     sha256(pubkey, pubsize, hash);     (int x = 0; x < 32; x++) {         printf("%.2x",hash[x]);     }     ec_key_free(key);     free(pubkey);     free(hash);     return 0; } 

as see i'm trying hash public key , print it. sha hash fails sha256_block_data_order. here's more information...

the version given as: openssl 1.0.1c 10 may 2012 pubsize set 65

after second i2o_ecpublickey, pubkey data somehow invalidated:

(gdb) p/x *pubkey @ 65 cannot access memory @ address 0x4d0ff1 

however before second i2o_ecpublickey, allocated pubkey data gives:

(gdb) p/x *pubkey @ 65 $1 = {0x0 <repeats 65 times>} 

so malloc allocation fine. second i2o_ecpublickey call doesn't work expected. how read ec public key bytes?

thank you.

i2o_ecpublickey moves pointer number of bytes written buffer, @ end of written. need pass in copy of pointer.

the following change fixes me:

            u_int8_t * pubkey = malloc(pubsize);     +       u_int8_t * pubkey2 = pubkey;     -       if(i2o_ecpublickey(key, &pubkey) != pubsize){     +       if(i2o_ecpublickey(key, &pubkey2) != pubsize){                 printf("pub key data fail\n"); 

Comments