OpenSSL i2o_ECPublicKey 无法正常工作。

8

我有这段代码:

#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公钥读入字节中?

谢谢。

1个回答

10

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接