aboutsummaryrefslogtreecommitdiff
path: root/utilities/gen_apikey.c
blob: 6f8d3f7d35186233d3897f5f0fc55a8435ca47f1 (plain)
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#ifdef NDEBUG
#error Asserts must work here
#endif

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <stdint.h>
#include <assert.h>


// This gives log2(64)*24 = 6*24 = 144 bits of entropy.
#define ALPHABET_SIZE 64
#define KEY_LENGTH 24


__attribute__((noreturn))
static void die(const char *msg) {
	fprintf(stderr, "%s\n", msg);
	exit(1);
}


//////////////////// RANDOM GENERATOR ////////////////////

struct randgen {
	FILE *urandom;
	uint8_t buffer[256];
	size_t cursor;
};

static void randgen_refresh(struct randgen *gen) {
	size_t nr = fread(gen->buffer, 1, sizeof gen->buffer, gen->urandom);
	if (nr < sizeof gen->buffer) die("Cannot read from /dev/urandom");
	gen->cursor = 0;
}

static struct randgen randgen_init(void) {
	FILE *f = fopen("/dev/urandom", "r");
	if (!f) die("Cannot open /dev/urandom");

	struct randgen gen;
	gen.urandom = f;
	randgen_refresh(&gen);

	return gen;
}

static uint8_t randgen_gen_byte(struct randgen *gen) {
	if (gen->cursor == sizeof gen->buffer) randgen_refresh(gen);
	return gen->buffer[gen->cursor++];
}

static uint64_t randgen_gen(struct randgen *gen, uint64_t below) {
	if (below == 0) return 0;

	int nbytes = 0;
	while (nbytes < 8 && (1ULL << (8 * nbytes)) < below) nbytes++;

	// This check allows us to do fearless modulo in the main loop
	if (nbytes == 8) assert(false && "'below' too large");

	const uint64_t gen_limit = 1ULL << (8 * nbytes);

	while (true) {
		uint64_t sample = 0;
		for (int i = 0; i < nbytes; i++) {
			sample |= (uint64_t)randgen_gen_byte(gen) << (8 * i);
		}

		if (sample < gen_limit - gen_limit % below) {
			return sample % below;
		}
	}
}


//////////////////// MAIN FUNCTIONALITY ////////////////////

static char gen_key_char(struct randgen *gen) {
	// 64 characters, so 6 bits
	static const char alphabet[] =
		"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_";
	assert(strlen(alphabet) == ALPHABET_SIZE);
	return alphabet[randgen_gen(gen, strlen(alphabet))];
}

int main() {
	struct randgen gen = randgen_init();

	char key[KEY_LENGTH + 1];
	for (size_t i = 0; i < KEY_LENGTH; i++) {
		key[i] = gen_key_char(&gen);
	}
	key[KEY_LENGTH] = '\0';

	printf("%s\n", key);
}