I have this 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 TO DATA ZERO\n");
return 1;
}
u_int8_t * pubKey = malloc(pubSize);
if(i2o_ECPublicKey(key, &pubKey) != pubSize){
printf("PUB KEY TO DATA FAIL\n");
return 1;
}
u_int8_t * hash = malloc(SHA256_DIGEST_LENGTH);
SHA256(pubKey, pubSize, hash);
for (int x = 0; x < 32; x++) {
printf("%.2x",hash[x]);
}
EC_KEY_free(key);
free(pubKey);
free(hash);
return 0;
}
As you see I'm trying to hash a public key and print it. The SHA hash fails sha256_block_data_order. Here's more information...
The version is given as: OpenSSL 1.0.1c 10 May 2012 pubSize is set to 65
After the second i2o_ECPublicKey, the pubKey data is somehow invalidated:
(gdb) p/x *pubKey @ 65
Cannot access memory at address 0x4d0ff1
However before the second i2o_ECPublicKey, the allocated pubKey data gives:
(gdb) p/x *pubKey @ 65
$1 = {0x0 <repeats 65 times>}
So the malloc allocation is fine. The second i2o_ECPublicKey call doesn't work as expected. How do I read a EC public key into bytes?
Thank you.
i2o_ECPublicKey moves your pointer by the number of bytes written to the buffer, so that it is at the end of what was written. You will need to pass in a copy of the pointer.
The following change fixes it for 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 TO DATA FAIL\n");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With