【问题标题】:OpenSSL i2o_ECPublicKey not workingOpenSSL i2o_ECPublicKey 不工作
【发布时间】:2012-06-10 00:21:20
【问题描述】:

我有这个代码:

#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;
}

如您所见,我正在尝试散列公钥并打印它。 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

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

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

所以 malloc 分配没问题。第二个 i2o_ECPublicKey 调用没有按预期工作。如何将 EC 公钥读入字节?

谢谢。

【问题讨论】:

    标签: c openssl segmentation-fault heap-memory bitcoin


    【解决方案1】:

    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");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-07-31
      • 2017-07-30
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      相关资源
      最近更新 更多