Properly handle key_len=0 for HMAC

The expectation when calling HMAC with key=NULL and keylen=0 is to compute
HMAC on the provided data with a key of length 0 instead of using the
"previous" key, which in the case of HMAC() is whatever bytes happen to be
left on the stack when the HMAC_CTX struct is allocated.

Change-Id: I52a95e262ee4e15f1af3136cb9c07f42f40ce122
Reviewed-on: https://boringssl-review.googlesource.com/2660
Reviewed-by: Adam Langley <agl@google.com>
diff --git a/crypto/hmac/hmac.c b/crypto/hmac/hmac.c
index 1d37b9e..bb96606 100644
--- a/crypto/hmac/hmac.c
+++ b/crypto/hmac/hmac.c
@@ -74,6 +74,13 @@
     out = static_out_buffer;
   }
 
+  /* If key_len is 0, the value of key doesn't matter. However, if we pass
+   * key == NULL into HMAC_Init, it interprets it to mean "use the previous
+   * value" instead of using a key of length 0. */
+  if (key == NULL && key_len == 0) {
+    key = static_out_buffer;
+  }
+
   HMAC_CTX_init(&ctx);
   if (!HMAC_Init(&ctx, key, key_len, evp_md) ||
       !HMAC_Update(&ctx, data, data_len) ||
diff --git a/crypto/hmac/hmac_test.c b/crypto/hmac/hmac_test.c
index 7b85196..def773b 100644
--- a/crypto/hmac/hmac_test.c
+++ b/crypto/hmac/hmac_test.c
@@ -145,6 +145,20 @@
     }
   }
 
+  /* Test that HMAC() functions corretly when called with key=NULL */
+  const struct test_st *test = &kTests[0];
+  if (NULL == HMAC(EVP_md5(), NULL, test->key_len, test->data,
+                   test->data_len, out, &out_len)) {
+    printf("HMAC failed.\n");
+    err++;
+  }
+
+  p = to_hex(out, out_len);
+  if (strcmp(p, test->hex_digest) != 0) {
+    printf("got %s instead of %s\n", p, test->hex_digest);
+    err++;
+  }
+
   if (err) {
     return 1;
   }