@@@ fltfmt mess
[mLib] / hash / siphash.c
diff --git a/hash/siphash.c b/hash/siphash.c
new file mode 100644 (file)
index 0000000..998283c
--- /dev/null
@@ -0,0 +1,74 @@
+/* -*-c-*-
+ *
+ * The SipHash-2-4 message authentication code
+ *
+ * (c) 2024 Straylight/Edgeware
+ */
+
+/*----- Licensing notice --------------------------------------------------*
+ *
+ * This file is part of the mLib utilities library.
+ *
+ * mLib is free software: you can redistribute it and/or modify it under
+ * the terms of the GNU Library General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or (at
+ * your option) any later version.
+ *
+ * mLib is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
+ * License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public
+ * License along with mLib.  If not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+ * USA.
+ */
+
+/*----- Header files ------------------------------------------------------*/
+
+#include "siphash.h"
+
+/*----- Main code ---------------------------------------------------------*/
+
+void siphash_setkey(struct siphash_key *k, const octet *p)
+  { LOAD64_L_(k->k0, p + 0); LOAD64_L_(k->k1, p + 8); }
+
+void siphash_init(struct siphash *s, const struct siphash_key *k)
+  { SIPHASH_INIT(s->a, s->b, s->c, s->d, k); s->n = s->msz = 0; }
+
+void siphash_hash(struct siphash *s, const void *p, size_t sz)
+{
+  const octet *q = p;
+  kludge64 m;
+  size_t n;
+
+  s->msz += sz;
+  n = SIPHASH_BLKSZ - s->n;
+  if (sz < n)
+    { memcpy(s->buf + s->n, q, sz); s->n += sz; return; }
+
+  if (s->n) {
+    memcpy(s->buf + s->n, q, n); q += n; sz -= n;
+    LOAD64_L_(m, s->buf); SIPHASH_WORD(s->a, s->b, s->c, s->d, m);
+  }
+  while (sz >= SIPHASH_BLKSZ) {
+    LOAD64_L_(m, q); SIPHASH_WORD(s->a, s->b, s->c, s->d, m);
+    q += SIPHASH_BLKSZ; sz -= SIPHASH_BLKSZ;
+  }
+  if (sz) memcpy(s->buf, q, sz);
+  s->n = sz;
+}
+
+kludge64 siphash_done(struct siphash *s)
+{
+  kludge64 z;
+
+  SIPHASH_FINAL(s->a, s->b, s->c, s->d, z, s->buf, s->n, s->msz);
+  return (z);
+}
+
+kludge64 siphash(const struct siphash_key *k, const void *p, size_t sz)
+  { kludge64 z; SIPHASH(k, z, p, sz); return (z); }
+
+/*----- That's all, folks -------------------------------------------------*/