David Hovsepyan
David Hovsepyan

Reputation: 626

openSSL: How to initialize EVP_PKEY object with the decoded key?

I have the following piece of code:

void Impl::sign()
{
    assert(!canonicalMessage_.empty());
    char* key = b64Decode(secureKey_);
    EVP_PKEY* pKey = NULL;
    EVP_MD_CTX* mdctx = NULL;
    std::size_t* slen = NULL;
    unsigned char** sig = NULL;
    *sig = NULL;
    // Create the Message Digest Context
    mdctx = EVP_MD_CTX_create();
    // Initialize the DigestSign operation.
    EVP_DigestSignInit(mdctx, NULL, EVP_sha256(), NULL, pKey);
    // Call update with the message
    const char* msg = canonicalMessage_.c_str();
    EVP_DigestSignUpdate(mdctx, msg, strlen(msg));

    // Obtain the length of the signature.
    EVP_DigestSignFinal(mdctx, NULL, slen);
    // Allocate memory for the signature based on size in slen
    *sig = (unsigned char*)OPENSSL_malloc(sizeof(unsigned char) * (*slen));
    // Obtain the signature
    EVP_DigestSignFinal(mdctx, *sig, slen);
    /* Clean up */
    if (*sig) OPENSSL_free(*sig);
    if(mdctx) EVP_MD_CTX_destroy(mdctx);
}

Here I'm getting decoded key using b64Decode() internal function (definition doesn't matter). My question is how I can pass pKey (initialized by key) to EVP_DigestSignInit function. I found the link (openSSL: how to initialize keys for public key encryption?) related to this, but unlike my case here file was used.

Upvotes: 1

Views: 1694

Answers (1)

David Hovsepyan
David Hovsepyan

Reputation: 626

Actually, I found the solution by downloading the source code specified here: https://wiki.openssl.org/index.php/EVP_Signing_and_Verifying

Solution:

unsigned char* key = b64Decode(secureKey_);
const EVP_MD* md = EVP_get_digestbyname("sha256");
EVP_PKEY* pKey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, key, EVP_MD_size(md));

Upvotes: 1

Related Questions