chiark / gitweb /
998283c96e49ada5aed7c6042c5711ff09758920
[mLib] / hash / siphash.c
1 /* -*-c-*-
2  *
3  * The SipHash-2-4 message authentication code
4  *
5  * (c) 2024 Straylight/Edgeware
6  */
7
8 /*----- Licensing notice --------------------------------------------------*
9  *
10  * This file is part of the mLib utilities library.
11  *
12  * mLib is free software: you can redistribute it and/or modify it under
13  * the terms of the GNU Library General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or (at
15  * your option) any later version.
16  *
17  * mLib is distributed in the hope that it will be useful, but WITHOUT
18  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
19  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Library General Public
20  * License for more details.
21  *
22  * You should have received a copy of the GNU Library General Public
23  * License along with mLib.  If not, write to the Free Software
24  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
25  * USA.
26  */
27
28 /*----- Header files ------------------------------------------------------*/
29
30 #include "siphash.h"
31
32 /*----- Main code ---------------------------------------------------------*/
33
34 void siphash_setkey(struct siphash_key *k, const octet *p)
35   { LOAD64_L_(k->k0, p + 0); LOAD64_L_(k->k1, p + 8); }
36
37 void siphash_init(struct siphash *s, const struct siphash_key *k)
38   { SIPHASH_INIT(s->a, s->b, s->c, s->d, k); s->n = s->msz = 0; }
39
40 void siphash_hash(struct siphash *s, const void *p, size_t sz)
41 {
42   const octet *q = p;
43   kludge64 m;
44   size_t n;
45
46   s->msz += sz;
47   n = SIPHASH_BLKSZ - s->n;
48   if (sz < n)
49     { memcpy(s->buf + s->n, q, sz); s->n += sz; return; }
50
51   if (s->n) {
52     memcpy(s->buf + s->n, q, n); q += n; sz -= n;
53     LOAD64_L_(m, s->buf); SIPHASH_WORD(s->a, s->b, s->c, s->d, m);
54   }
55   while (sz >= SIPHASH_BLKSZ) {
56     LOAD64_L_(m, q); SIPHASH_WORD(s->a, s->b, s->c, s->d, m);
57     q += SIPHASH_BLKSZ; sz -= SIPHASH_BLKSZ;
58   }
59   if (sz) memcpy(s->buf, q, sz);
60   s->n = sz;
61 }
62
63 kludge64 siphash_done(struct siphash *s)
64 {
65   kludge64 z;
66
67   SIPHASH_FINAL(s->a, s->b, s->c, s->d, z, s->buf, s->n, s->msz);
68   return (z);
69 }
70
71 kludge64 siphash(const struct siphash_key *k, const void *p, size_t sz)
72   { kludge64 z; SIPHASH(k, z, p, sz); return (z); }
73
74 /*----- That's all, folks -------------------------------------------------*/