initial commit
[project/unetd.git] / siphash.h
1 /* Copyright (C) 2016 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
2 *
3 * This file is provided under a dual BSD/GPLv2 license.
4 *
5 * SipHash: a fast short-input PRF
6 * https://131002.net/siphash/
7 *
8 * This implementation is specifically for SipHash2-4 for a secure PRF
9 * and HalfSipHash1-3/SipHash1-3 for an insecure PRF only suitable for
10 * hashtables.
11 */
12
13 #ifndef _LINUX_SIPHASH_H
14 #define _LINUX_SIPHASH_H
15
16 #include <stdint.h>
17 #include <stdlib.h>
18 #include <stdbool.h>
19 #include <libubox/utils.h>
20
21 #define SIPHASH_ALIGNMENT __alignof__(uint64_t)
22 typedef struct {
23 uint64_t key[2];
24 } siphash_key_t;
25
26 static inline uint16_t get_unaligned_le16(const uint8_t *p)
27 {
28 return p[0] | p[1] << 8;
29 }
30
31 static inline uint32_t get_unaligned_le32(const uint8_t *p)
32 {
33 return p[0] | p[1] << 8 | p[2] << 16 | p[3] << 24;
34 }
35
36 static inline uint64_t get_unaligned_le64(const uint8_t *p)
37 {
38 return (uint64_t)get_unaligned_le32(p + 4) << 32 |
39 get_unaligned_le32(p);
40 }
41
42 static inline bool siphash_key_is_zero(const siphash_key_t *key)
43 {
44 return !(key->key[0] | key->key[1]);
45 }
46
47 uint64_t siphash(const void *data, size_t len, const siphash_key_t *key);
48
49 static inline void siphash_to_le64(void *dest, const void *data, size_t len,
50 const siphash_key_t *key)
51 {
52 uint64_t hash = siphash(data, len, key);
53
54 *(uint64_t *)dest = cpu_to_le64(hash);
55 }
56
57 #endif /* _LINUX_SIPHASH_H */