1 /* Copyright (c) 2019, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <stdint.h>
16 #include <string.h>
17 
18 #include <openssl/siphash.h>
19 
20 #include "../internal.h"
21 
22 
siphash_round(uint64_t v[4])23 static void siphash_round(uint64_t v[4]) {
24   v[0] += v[1];
25   v[2] += v[3];
26   v[1] = (v[1] << 13) | (v[1] >> (64 - 13));
27   v[3] = (v[3] << 16) | (v[3] >> (64 - 16));
28   v[1] ^= v[0];
29   v[3] ^= v[2];
30   v[0] = (v[0] << 32) | (v[0] >> 32);
31   v[2] += v[1];
32   v[0] += v[3];
33   v[1] = (v[1] << 17) | (v[1] >> (64 - 17));
34   v[3] = (v[3] << 21) | (v[3] >> (64 - 21));
35   v[1] ^= v[2];
36   v[3] ^= v[0];
37   v[2] = (v[2] << 32) | (v[2] >> 32);
38 }
39 
SIPHASH_24(const uint64_t key[2],const uint8_t * input,size_t input_len)40 uint64_t SIPHASH_24(const uint64_t key[2], const uint8_t *input,
41                     size_t input_len) {
42   const size_t orig_input_len = input_len;
43 
44   uint64_t v[4];
45   v[0] = key[0] ^ UINT64_C(0x736f6d6570736575);
46   v[1] = key[1] ^ UINT64_C(0x646f72616e646f6d);
47   v[2] = key[0] ^ UINT64_C(0x6c7967656e657261);
48   v[3] = key[1] ^ UINT64_C(0x7465646279746573);
49 
50   while (input_len >= sizeof(uint64_t)) {
51     uint64_t m;
52     memcpy(&m, input, sizeof(m));
53     v[3] ^= m;
54     siphash_round(v);
55     siphash_round(v);
56     v[0] ^= m;
57 
58     input += sizeof(uint64_t);
59     input_len -= sizeof(uint64_t);
60   }
61 
62   union {
63     uint8_t bytes[8];
64     uint64_t word;
65   } last_block;
66   last_block.word = 0;
67   OPENSSL_memcpy(last_block.bytes, input, input_len);
68   last_block.bytes[7] = orig_input_len & 0xff;
69 
70   v[3] ^= last_block.word;
71   siphash_round(v);
72   siphash_round(v);
73   v[0] ^= last_block.word;
74 
75   v[2] ^= 0xff;
76   siphash_round(v);
77   siphash_round(v);
78   siphash_round(v);
79   siphash_round(v);
80 
81   return v[0] ^ v[1] ^ v[2] ^ v[3];
82 }
83