OpenSSL i2o_ECPublicKey无效

Mat*_*ell 8 c heap openssl segmentation-fault bitcoin

我有这个代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

如您所见,我正在尝试哈希公钥并打印它.SHA哈希失败sha256_block_data_order.这里有更多信息......

版本如下:OpenSSL 1.0.1c 2012年5月10日pubSize设置为65

在第二个i2o_ECPublicKey之后,pubKey数据以某种方式失效:

(gdb) p/x *pubKey @ 65
Cannot access memory at address 0x4d0ff1
Run Code Online (Sandbox Code Playgroud)

但是在第二个i2o_ECPublicKey之前,分配的pubKey数据给出:

(gdb) p/x *pubKey @ 65
$1 = {0x0 <repeats 65 times>}
Run Code Online (Sandbox Code Playgroud)

所以malloc分配很好.第二个i2o_ECPublicKey调用无法按预期工作.如何将EC公钥读入字节?

谢谢.

Mic*_*ton 9

i2o_ECPublicKey将指针移动到写入缓冲区的字节数,以便它在写入的结尾处.您需要传入指针的副本.

以下更改为我修复了它:

            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");
Run Code Online (Sandbox Code Playgroud)