469c74abaedea0a7a0c10b72fc6d31b233de7bc6
[tinc] / src / xoshiro.c
1 /*  Written in 2018 by David Blackman and Sebastiano Vigna (vigna@acm.org)
2
3 To the extent possible under law, the author has dedicated all copyright
4 and related and neighboring rights to this software to the public domain
5 worldwide. This software is distributed without any warranty.
6
7 See <http://creativecommons.org/publicdomain/zero/1.0/>. */
8
9 #include <stdint.h>
10
11 #include "crypto.h"
12
13 /* This is xoshiro256** 1.0, one of our all-purpose, rock-solid
14    generators. It has excellent (sub-ns) speed, a state (256 bits) that is
15    large enough for any parallel application, and it passes all tests we
16    are aware of.
17
18    For generating just floating-point numbers, xoshiro256+ is even faster.
19
20    The state must be seeded so that it is not everywhere zero. If you have
21    a 64-bit seed, we suggest to seed a splitmix64 generator and use its
22    output to fill s. */
23
24 static inline uint64_t rotl(const uint64_t x, int k) {
25         return (x << k) | (x >> (64 - k));
26 }
27
28 static uint64_t s[4];
29
30 uint64_t xoshiro(void) {
31         const uint64_t result = rotl(s[1] * 5, 7) * 9;
32
33         const uint64_t t = s[1] << 17;
34
35         s[2] ^= s[0];
36         s[3] ^= s[1];
37         s[1] ^= s[2];
38         s[0] ^= s[3];
39
40         s[2] ^= t;
41
42         s[3] = rotl(s[3], 45);
43
44         return result;
45 }
46
47 void prng_init(void) {
48         do {
49                 randomize(s, sizeof(s));
50         } while(!s[0] && !s[1] && !s[2] && !s[3]);
51 }
52
53 void prng_randomize(void *buf, size_t buflen) {
54         uint8_t *p = buf;
55         uint64_t value;
56
57         while(buflen > sizeof(value)) {
58                 value = xoshiro();
59                 memcpy(p, &value, sizeof(value));
60                 p += sizeof(value);
61                 buflen -= sizeof(value);
62         }
63
64         if(!buflen) {
65                 return;
66         }
67
68         value = xoshiro();
69         memcpy(p, &value, buflen);
70 }