OpenSSL缓冲区到EVP_PKEY

问题描述 投票:0回答:1

我正在编程一个通过通过连接到Google服务器的TCP套接字发送消息来参与TLS 1.2握手的客户端。我正在使用ECDH密钥交换方法。

我正在尝试使用this代码导出共享机密。

我通过serverKeyExchange消息接收到密钥并将其存储在缓冲区中,所以我的问题是:如何从缓冲区中生成EVP_PKEY?我在this帖子中找到了可能的解决方案,并尝试了:

i2d_PublicKey(peerkey, (unsigned char **) &server_pub_key)

但是当我运行代码时,在此步骤中出现错误:

/* Provide the peer public key */
    if(1 != EVP_PKEY_derive_set_peer(ctx, peerkey)) handleErrors();

这使我认为我没有成功获取服务器的公共密钥。

有任何建议吗?我什至不知道密钥是否已成功编码?

openssl tls1.2 public-key ecdh
1个回答
0
投票

如果拥有原始公共密钥,则必须使用正确的参数创建EC_Key。

EVP_PKEY * get_peerkey(const unsigned char * buffer, size_t buffer_len)
{
    EC_KEY *tempEcKey = NULL;
    EVP_PKEY *peerkey = NULL;

    // change this if another curve is required
    tempEcKey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
    if(tempEcKey == NULL) {
        handleErrors();
    }

    if(EC_KEY_oct2key(tempEcKey, buffer, buffer_len, NULL) != 1)  {
        handleErrors();
    }

    if(EC_KEY_check_key(tempEcKey) != 1) {
        handleErrors();
    }

    peerkey = EVP_PKEY_new();
    if(peerkey == NULL) {
        handleErrors();
    }

    if(EVP_PKEY_assign_EC_KEY(peerkey, tempEcKey)!= 1) {
        handleErrors();
    }

    return peerkey;
}

如果您具有公钥作为ASN.1序列,则可以使用内部转换方法:

EVP_PKEY* get_peerkey(const unsigned char *buffer, size_t buffer_len)
{
    EVP_PKEY *peerkey = NULL;       
    const unsigned char *helper = buffer;

    // from "openssl/x509.h"
    peerkey = d2i_PUBKEY(NULL, &helper, buffer_len);
    if (!peerkey) {
        handleErrors();
        return NULL;
    }

    return peerkey;
}
© www.soinside.com 2019 - 2024. All rights reserved.