/
aesrand.c
82 lines (71 loc) · 1.98 KB
/
aesrand.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/*
* ZMap Copyright 2013 Regents of the University of Michigan
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*/
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <string.h>
#include "../lib/logger.h"
#include "../lib/rijndael-alg-fst.h"
#include "../lib/random.h"
#include "../lib/xalloc.h"
#include "aesrand.h"
#define AES_ROUNDS 10
#define AES_BLOCK_WORDS 4
#define AES_KEY_BYTES 16
#define AES_KEY_BITS (AES_KEY_BYTES * 8)
#define OUTPUT_BYTES 16
struct aesrand {
uint32_t input[AES_BLOCK_WORDS];
uint32_t sched[(AES_ROUNDS + 1) * 4];
uint8_t output[OUTPUT_BYTES];
bool remaining;
};
static aesrand_t *_aesrand_init(uint8_t *key)
{
aesrand_t *aes = xmalloc(sizeof(aesrand_t));
memset(&aes->input, 0, AES_BLOCK_WORDS * 4);
if (rijndaelKeySetupEnc(aes->sched, key, AES_KEY_BITS) != AES_ROUNDS) {
log_fatal("aesrand", "could not initialize AES key");
}
memset(aes->output, 0, OUTPUT_BYTES);
aes->remaining = false;
return aes;
}
aesrand_t *aesrand_init_from_seed(uint64_t seed)
{
uint8_t key[AES_KEY_BYTES];
memset(key, 0, AES_KEY_BYTES);
for (uint8_t i = 0; i < sizeof(seed); ++i) {
key[i] = (uint8_t)((seed >> 8 * i) & 0xFF);
}
return _aesrand_init(key);
}
aesrand_t *aesrand_init_from_random(void)
{
uint8_t key[AES_KEY_BYTES];
if (!random_bytes(key, AES_KEY_BYTES)) {
log_fatal("aesrand", "Couldn't get random bytes");
}
return _aesrand_init(key);
}
uint64_t aesrand_getword(aesrand_t *aes)
{
uint64_t retval;
if (aes->remaining) {
memcpy(&retval, &aes->output[sizeof(retval)], sizeof(retval));
aes->remaining = false;
return retval;
}
memcpy(aes->input, aes->output, sizeof(aes->input));
rijndaelEncrypt(aes->sched, AES_ROUNDS, (uint8_t *)aes->input,
aes->output);
memcpy(&retval, aes->output, sizeof(retval));
aes->remaining = true;
return retval;
}