简体   繁体   English

OpenSSL 公钥从 EVP_PKEY 到缓冲区

[英]OpenSSL public key from EVP_PKEY to buffer

I'm programming a client that partecipates in a TLS 1.2 handshake by sending messages through a TCP socket connected to Google's server.我正在编写一个通过连接到 Google 服务器的 TCP 套接字发送消息来参与 TLS 1.2 握手的客户端。 I'm using the ECDH key exchange method.我正在使用 ECDH 密钥交换方法。

I generated the client keypair using this code, and now I want to send the ClientKeyExchange to the server containing the public key.我使用代码生成了客户端密钥对,现在我想将 ClientKeyExchange 发送到包含公钥的服务器。 In order to do that I first need to transfer the key containted in the EVP_PKEY into a buffer.为此,我首先需要将 EVP_PKEY 中包含的密钥传输到缓冲区中。 I already did the opposite transformation for the server peerkey but I haven't figured out what to do now.我已经对服务器 peerkey 进行了相反的转换,但我现在还没有弄清楚该怎么做。

My code is:我的代码是:

void get_buffer(EVP_PKEY * pkey, unsigned char * client_pub_key, int pkeyLen) {

   EC_KEY *tempEcKey = NULL;

   tempEcKey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);

   if(0 == (EVP_PKEY_set1_EC_KEY(pkey, tempEcKey))){
      handleErrors();
   }

   const EC_GROUP * group = EC_KEY_get0_group(tempEcKey);
   point_conversion_form_t form = EC_GROUP_get_point_conversion_form(group);

   //write in the buffer
   pkeyLen = EC_KEY_key2buf(tempEcKey, form, *client_pub_key, NULL);
   if(pkeyLen == 0){
      handleErrors();
   } 
}

The code causes a segmentation fault when calling EVP_PKEY_set1_EC_KEY(pkey, tempEcKey) .该代码在调用EVP_PKEY_set1_EC_KEY(pkey, tempEcKey)时会导致分段错误。

What am I doing wrong?我究竟做错了什么?

I also looked at the EVP_PKEY_get_raw_public_key() function but it doesn't work either.我还查看了EVP_PKEY_get_raw_public_key() function 但它也不起作用。 docs 文档

You need to get the EC_KEY from the EVP_PKEY instead of EC_KEY_new_by_curve_name and EVP_PKEY_set1_EC_KEY use EVP_PKEY_get0_EC_KEY .您需要从 EVP_PKEY 获取 EC_KEY 而不是EC_KEY_new_by_curve_nameEVP_PKEY_set1_EC_KEY使用EVP_PKEY_get0_EC_KEY

EC_KEY_key2buf allocates a buffer for you and is not using a pre allocated buffer, this allocated buffer must be freed using OPENSSL_free . EC_KEY_key2buf为您分配一个缓冲区并且没有使用预分配的缓冲区,这个分配的缓冲区必须使用OPENSSL_free释放。

void get_buffer(EVP_PKEY * pkey, unsigned char ** client_pub_key, int *pkeyLen) {
    EC_KEY *tempEcKey = NULL;

    tempEcKey = EVP_PKEY_get0_EC_KEY(pkey);
    if(tempEcKey == NULL) {
        handleErrors("Getting EC_KEY from EVP_PKEY");
        return;
    }

    const EC_GROUP * group = EC_KEY_get0_group(tempEcKey);
    point_conversion_form_t form = EC_GROUP_get_point_conversion_form(group);

    *pkeyLen = EC_KEY_key2buf(tempEcKey, form, client_pub_key, NULL);
    if(*pkeyLen == 0){
       handleErrors("Creating buffer from key");
       return;
    } 
}

I have encountered the same problem and this is working for me:我遇到了同样的问题,这对我有用:

std::size_t len = 32;
uint8_t* pubkey = new uint8_t[len];

EVP_PKEY_get_raw_public_key(pkey, pubkey, &len);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM