2016-01-21 21:11:47 +01:00
|
|
|
#include "pseudorand.h"
|
|
|
|
#include <assert.h>
|
2016-06-28 23:19:20 +02:00
|
|
|
#include <ccan/crypto/siphash24/siphash24.h>
|
2016-01-21 21:11:47 +01:00
|
|
|
#include <ccan/err/err.h>
|
|
|
|
#include <ccan/isaac/isaac64.h>
|
|
|
|
#include <ccan/likely/likely.h>
|
2016-06-28 23:19:20 +02:00
|
|
|
#include <sodium/randombytes.h>
|
2016-01-21 21:11:47 +01:00
|
|
|
#include <stdbool.h>
|
2016-06-28 23:19:20 +02:00
|
|
|
#include <string.h>
|
2016-01-21 21:11:47 +01:00
|
|
|
|
|
|
|
static struct isaac64_ctx isaac64;
|
2016-06-28 23:19:20 +02:00
|
|
|
static struct siphash_seed siphashseed;
|
2016-01-21 21:11:47 +01:00
|
|
|
static bool pseudorand_initted = false;
|
|
|
|
|
2016-06-28 23:19:20 +02:00
|
|
|
static void init_if_needed(void)
|
2016-01-21 21:11:47 +01:00
|
|
|
{
|
|
|
|
if (unlikely(!pseudorand_initted)) {
|
|
|
|
unsigned char seedbuf[16];
|
|
|
|
|
2016-06-28 23:19:20 +02:00
|
|
|
randombytes_buf(seedbuf, sizeof(seedbuf));
|
2016-01-21 21:11:47 +01:00
|
|
|
|
|
|
|
isaac64_init(&isaac64, seedbuf, sizeof(seedbuf));
|
2016-06-28 23:19:20 +02:00
|
|
|
memcpy(&siphashseed, seedbuf, sizeof(siphashseed));
|
2016-01-21 21:11:47 +01:00
|
|
|
pseudorand_initted = true;
|
|
|
|
}
|
2016-06-28 23:19:20 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
uint64_t pseudorand(uint64_t max)
|
|
|
|
{
|
|
|
|
init_if_needed();
|
|
|
|
|
2016-01-21 21:11:47 +01:00
|
|
|
assert(max);
|
|
|
|
return isaac64_next_uint(&isaac64, max);
|
|
|
|
}
|
2016-06-28 23:19:20 +02:00
|
|
|
|
|
|
|
const struct siphash_seed *siphash_seed(void)
|
|
|
|
{
|
|
|
|
init_if_needed();
|
|
|
|
|
|
|
|
return &siphashseed;
|
|
|
|
}
|
|
|
|
|