Reduce memory allocations due to HMAC() and EVP_MD_*().
[tinc] / src / openssl / digest.c
index 9c3ab1e..d51dcaa 100644 (file)
@@ -66,9 +66,13 @@ digest_t *digest_open_by_nid(int nid, int maclength) {
 }
 
 bool digest_set_key(digest_t *digest, const void *key, size_t len) {
-       digest->key = xrealloc(digest->key, len);
-       memcpy(digest->key, key, len);
-       digest->keylength = len;
+       digest->hmac_ctx = HMAC_CTX_new();
+       HMAC_Init_ex(digest->hmac_ctx, key, len, digest->digest, NULL);
+
+       if(!digest->hmac_ctx) {
+               abort();
+       }
+
        return true;
 }
 
@@ -77,7 +81,14 @@ void digest_close(digest_t *digest) {
                return;
        }
 
-       free(digest->key);
+       if(digest->md_ctx) {
+               EVP_MD_CTX_destroy(digest->md_ctx);
+       }
+
+       if(digest->hmac_ctx) {
+               HMAC_CTX_free(digest->hmac_ctx);
+       }
+
        free(digest);
 }
 
@@ -85,27 +96,28 @@ bool digest_create(digest_t *digest, const void *indata, size_t inlen, void *out
        size_t len = EVP_MD_size(digest->digest);
        unsigned char tmpdata[len];
 
-       if(digest->key) {
-               if(!HMAC(digest->digest, digest->key, digest->keylength, indata, inlen, tmpdata, NULL)) {
+       if(digest->hmac_ctx) {
+               if(!HMAC_Init_ex(digest->hmac_ctx, NULL, 0, NULL, NULL)
+                               || !HMAC_Update(digest->hmac_ctx, indata, inlen)
+                               || !HMAC_Final(digest->hmac_ctx, tmpdata, NULL)) {
                        logger(DEBUG_ALWAYS, LOG_DEBUG, "Error creating digest: %s", ERR_error_string(ERR_get_error(), NULL));
                        return false;
                }
        } else {
-               EVP_MD_CTX *ctx = EVP_MD_CTX_create();
+               if(!digest->md_ctx) {
+                       digest->md_ctx = EVP_MD_CTX_create();
+               }
 
-               if(!ctx) {
+               if(!digest->md_ctx) {
                        abort();
                }
 
-               if(!EVP_DigestInit(ctx, digest->digest)
-                               || !EVP_DigestUpdate(ctx, indata, inlen)
-                               || !EVP_DigestFinal(ctx, tmpdata, NULL)) {
+               if(!EVP_DigestInit(digest->md_ctx, digest->digest)
+                               || !EVP_DigestUpdate(digest->md_ctx, indata, inlen)
+                               || !EVP_DigestFinal(digest->md_ctx, tmpdata, NULL)) {
                        logger(DEBUG_ALWAYS, LOG_DEBUG, "Error creating digest: %s", ERR_error_string(ERR_get_error(), NULL));
-                       EVP_MD_CTX_destroy(ctx);
                        return false;
                }
-
-               EVP_MD_CTX_destroy(ctx);
        }
 
        memcpy(outdata, tmpdata, digest->maclength);