This repository has been archived by the owner on Jun 17, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rnd-sodium.c
96 lines (82 loc) · 2.36 KB
/
rnd-sodium.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
/*
* Secure Random Number Generator
*
* This solution must exclusively read from the kernel's
* Cryptographically Secure Pseudorandom Number Generator (CSPRNG)
* and fail closed.
* Userspace Random Number Generators (RNGs) and insecure RNG
* fallbacks will not be accepted.
*
* Dependency:
*
* Ubuntu:
* libsodium-dev
*
* Other systems:
* Documentation at https://download.libsodium.org/libsodium/content/installation/
*
* Usage:
*
* Step 1: make
* Step 2: ./rnd-sodium [number]
*
* Alternative method:
*
* https://www.nist.gov/programs-projects/nist-randomness-beacon
*
* References:
*
* - https://www.2uo.de/myths-about-urandom/
* - https://sockpuppet.org/blog/2014/02/25/safely-generate-random-numbers/
* - https://blog.cr.yp.to/20140205-entropy.html
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <sodium.h>
int main(int argc, char *argv[])
{
/*
* Hang the program execution if no arguments are provided.
*/
if (argc <= 1) {
fprintf( stderr, "Usage: ./rnd-sodium [number]\n" );
return -1;
}
/*
* Hang the program execution if libsodium cannot securely initiate.
*/
if ( sodium_init() < 0 ) {
fprintf( stderr, "Error initializing libsodium.\n" );
return -1;
}
/*
* Define the variables.
*/
char buf_string[4096];
uint64_t random_number;
uint64_t top = atoi( argv[1] );
/*
* buf_string will be an array of 4096 random bytes, not null-terminated
*/
randombytes_buf(buf_string, 4096);
/*
* The randombytes_uniform() function returns an unpredictable value
* between 0 and upper_bound (excluded).
* Unlike randombytes_random() % upper_bound, it guarantees a uniform
* distribution of the possible output values even when upper_bound
* is not a power of 2. Note that an upper_bound < 2 leaves only a single
* element to be chosen, namely 0.
*/
random_number = randombytes_uniform(top);
/*
* Add 1 to random_number to make top included and 0 excluded from possible
* values.
*/
random_number += 1;
/*
* Print random_number.
*/
printf("%lu\n", random_number);
return 0;
}