summaryrefslogtreecommitdiff
path: root/src/random.c
blob: de947830162fe6f914498d4b78a0ba59c15f9e68 (plain) (blame)
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
#include <s.h>

#include <assert.h>
#include <stdio.h>

#include "random.h"



static FILE *
FH = NULL;



int
random_init(void) {
	int rc = -1;

	FH = fopen("/dev/urandom", "r");
	if (FH == NULL) {
		perror("fopen()");
		goto out;
	}

	rc = 0;
out:
	return rc;
}

int
random_destroy(void) {
	if (FH == NULL) {
		return 0;
	}

	int rc = -1;

	if (fclose(FH)) {
		perror("fclose()");
		goto out;
	}

	rc = 0;
out:
	FH = NULL;
	return rc;
}

static int
random_generate(const unsigned long long length, unsigned char *const out) {
	int rc = -1;

	const size_t read_count = fread(out, 1U, length, FH);
	if (ferror(FH)) {
		perror("fread()");
		goto out;
	}
	assert(read_count == length);

	rc = 0;
out:
	return rc;
}

void
random_bytes(unsigned char *const out, const unsigned long long length) {
	assert(FH != NULL);
	assert(random_generate(length, out) == 0);
}

void
randombytes(unsigned char *const out, const unsigned long long length) {
	random_bytes(out, length);
}