Subject: [PATCH] Add nonce support for gnutls-hash-mac

From: SK Kim <[email-masked]>
Date: Sat, 9 Sep 2023 00:58:52 +0900

Hi,

As far as I understood, currently `gnutls-hash-mac' does not support nonce
input, so there is no way to properly hash with some MAC algorithms which
require nonce. (e.g AES-GMAC-128)
So I suggest adding an optional argument NONCE to `gnutls-hash-mac' to
support MAC algorithms with nonce.

What I have tested after applying the attached patch are as below.
1. AES-GMC-128/192/256 works correctly.
2. NONCE does not affect SHA256/SHA512 hash results, even if presented.

Since NONCE is added as an optional argument, I believe it will not even
affect existing code using the 'gnutls-hash-mac' function.

Thanks.

Seungki Kim
diff --git a/src/gnutls.c b/src/gnutls.c
index e3f1093d977..26dd17e673c 100644
--- a/src/gnutls.c
+++ b/src/gnutls.c
@@ -2740,7 +2740,7 @@ DEFUN ("gnutls-digests", Fgnutls_digests, Sgnutls_digests, 0, 0, 0,
   return digest_algorithms;
 }
 
-DEFUN ("gnutls-hash-mac", Fgnutls_hash_mac, Sgnutls_hash_mac, 3, 3, 0,
+DEFUN ("gnutls-hash-mac", Fgnutls_hash_mac, Sgnutls_hash_mac, 3, 4, 0,
        doc: /* Hash INPUT with HASH-METHOD and KEY into a unibyte string.
 
 Return nil on error.
@@ -2752,11 +2752,16 @@ DEFUN ("gnutls-hash-mac", Fgnutls_hash_mac, Sgnutls_hash_mac, 3, 3, 0,
 The INPUT can also be specified as a buffer or string or in other
 ways.
 
+The NONCE can also be specified as a buffer or string or in other
+ways. If MAC algorithm does not require nonce, the optional argument
+NONCE is ignored even if presented.
+
+
 The alist of MAC algorithms can be obtained with `gnutls-macs'.  The
 HASH-METHOD may be a string or symbol matching a key in that alist, or
 a plist with the `:mac-algorithm-id' numeric property, or the number
 itself. */)
-  (Lisp_Object hash_method, Lisp_Object key, Lisp_Object input)
+  (Lisp_Object hash_method, Lisp_Object key, Lisp_Object input, Lisp_Object nonce)
 {
   if (BUFFERP (input) || STRINGP (input))
     input = list1 (input);
@@ -2813,6 +2818,23 @@ DEFUN ("gnutls-hash-mac", Fgnutls_hash_mac, Sgnutls_hash_mac, 3, 3, 0,
     error ("GnuTLS MAC %s initialization failed: %s",
 	   gnutls_mac_get_name (gma), emacs_gnutls_strerror (ret));
 
+  if (!NILP (nonce))
+    {
+      if (BUFFERP (nonce) || STRINGP (nonce))
+        nonce = list1 (nonce);
+
+      CHECK_CONS (nonce);
+
+      ptrdiff_t nstart_byte, nend_byte;
+      const char *ndata
+        = extract_data_from_object (nonce, &nstart_byte, &nend_byte);
+      if (ndata == NULL)
+        error ("GnuTLS MAC nonce extraction failed");
+
+      gnutls_hmac_set_nonce (hmac,
+			     ndata + nstart_byte, nend_byte - nstart_byte);
+    }
+
   ptrdiff_t istart_byte, iend_byte;
   const char *idata
     = extract_data_from_object (input, &istart_byte, &iend_byte);