簡體   English   中英

OpenSSL 服務器公鑰從緩沖區到 EVP_PKEY

[英]OpenSSL server public key from buffer to EVP_PKEY

我正在編寫一個通過連接到 Google 服務器的 TCP 套接字發送消息來參與 TLS 1.2 握手的客戶端。 我正在使用 ECDH 密鑰交換方法。

我正在嘗試使用代碼導出共享秘密。

我通過 serverKeyExchange 消息接收到密鑰並將其存儲在緩沖區中,所以我的問題是:如何從緩沖區生成 EVP_PKEY? 我在這篇文章中找到了一個可能的解決方案並嘗試了:

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

但是當我運行代碼時,這一步出現錯誤:

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

這讓我覺得我沒有成功檢索服務器公鑰。

有什么建議么? 我怎么知道密鑰是否已成功編碼?

如果您擁有原始公鑰,則必須使用正確的參數創建 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM