Emck
Emck

Reputation: 95

OpenSSL DigestInit_ex

I'm decrypting incoming packets with OpenSSL and i'm using EVP library to do the job and i first decrypt the packet and then calculate the hmac.

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, key, iv);
EVP_DecryptUpdate(ctx, payload, &len, payload, data_len);
EVP_DecryptFinal_ex(ctx, payload + len, &len);

and with the HMAC

EVP_PKEY *skey = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL, hmac_key, 32);
EVP_DigestInit_ex(md_ctx, EVP_sha256(), NULL);
EVP_DigestSignInit(md_ctx, NULL, md, NULL, skey);
EVP_DigestSignUpdate(md_ctx, hmac_payload, m+13);
EVP_DigestSignFinal(md_ctx, buff, &size);

Now, this works just fine but the problem is having to call the init functions every time before i decrypt and calculate HMAC which is not efficient because every packet has same decryption and HMAC key.

Is it possible to do the decryption and hmac calculation for each packet with same keys without calling the init functions every time ? Obviously if i remove them from my code the decryption and HMAC calculation do not work correctly.

Upvotes: 1

Views: 661

Answers (1)

Castaglia
Castaglia

Reputation: 3089

No, it is not possible with the OpenSSL implementation.

In OpenSSL terminology, a "context" like EVP_CIPHER_CTX or EVP_MD_CTX is a container for all of the state that is needed for one encryption/decryption operation, or one digest. To reset a context for the next encryption/decryption, or digest (and thus to clear all the previous state), the calls to EVP_DigestInit_ex() and EVP_DecryptInit_ex() are necessary.

Another way to look at this is that you (the programmer) could be changing the cipher/digest algorithms, or other parameters, on each EVP_DigestInit_ex() or EVP_DecryptInit_ex() call; the underlying context does not know your intention. Thus calling the initialization function, each time for re-using that context structure, prepares that structure for these initialization parameters (which might be different the next time).

Hope this helps!

Upvotes: 2

Related Questions