在给定Base64编码的情况下,如何为对等密钥创建EVP_KEY?

时间:2015-07-31 00:11:51

标签: c++ openssl diffie-hellman

使用OpenSSL,我创建了我的Diffie-Hellman私钥/公钥,并收到了我的对等公钥。我可以将我的对等密钥从Base64字符串解码为字节数组,但是如何将其解析为我原始的公钥/私钥EVP_KEY结构,以便它可以与EVP_PKEY_derive()一起使用来生成共享密钥?

目前还不清楚究竟应该做些什么来创建“peerkey”EVP_PKEY,但这是我的代码,它可以用来拍摄它。

void CreateSharedKey(string &peerKey64)
{
    EVP_PKEY *publicKey;  // Created earlier
    EVP_PKEY *peerKey;

    // Decode peer key
    unsigned char *pBuff;
    int buffLen = base64Decode(peerKey64, &pBuff);
    const unsigned char *pConst = pBuff;

    // Create peer key
    peerKey = d2i_PUBKEY(NULL, &pConst, buffLen);
    if (peerKey == NULL)
        return;

    // Create shared key context
    EVP_PKEY_CTX *ctxShared;
    ctxShared = EVP_PKEY_CTX_new(publicKey, NULL);
    if (ctxShared == NULL)
        return;

    // Initialize for deriving shared key
    if (EVP_PKEY_derive_init(ctxShared) <= 0)
        return;

    // Add peer key to context
    if (int rc = EVP_PKEY_derive_set_peer(ctxShared, peerKey) <= 0)
        return;

    // Determine buffer length for shared key
    size_t sharedKeyBufferSize;
    if (EVP_PKEY_derive(ctxShared, NULL, &sharedKeyBufferSize) <= 0)
        return;

    // Allocate buffer for shared key
    unsigned char *sharedKeyBuffer = new unsigned char[sharedKeyBufferSize];
    if (sharedKeyBuffer == NULL)
        return;

    // Derive the shared key
    if (EVP_PKEY_derive(ctxShared, sharedKeyBuffer, &sharedKeyBufferSize) <= 0)
    {
        unsigned long error = ERR_get_error();
        cout << "Failed to derive shared key. Error code = " << error << std::endl;
        cout << ERR_reason_error_string(error) << std::endl;

        return;
    }

    // Free shared key context
    EVP_PKEY_CTX_free(ctxShared);

    // Create Base64 shared key string
    base64Encode(sharedKeyStr, sharedKeyBuffer, sharedKeyBufferSize);
}

OpenSSL错误输出如下:

无法将对等方添加到共享密钥上下文。错误代码= 101298329 不同的参数

当它是从基于原始publicKey中已存在的参数的Context派生时,它如何具有不同的参数?

0 个答案:

没有答案