]> diplodocus.org Git - nmh/blob - sbr/m_rand.c
76e5e17f3fecca82f2dd9807cf99fa5af0df66cb
[nmh] / sbr / m_rand.c
1 /* m_rand.c -- provides pseudorandom bytes
2 *
3 * This code is Copyright (c) 2012, by the authors of nmh. See the
4 * COPYRIGHT file in the root directory of the nmh distribution for
5 * complete copyright information.
6 */
7
8 #include <stdlib.h> /* for abs(), srand(), rand(), arc4random() */
9 #include <stdbool.h>
10 #include <stdio.h> /* for fopen(), fread(), fclose() */
11 #include <unistd.h> /* for getpid() */
12 #include <time.h> /* for time() */
13
14 #include <config.h>
15 #include "m_rand.h"
16
17 #if !HAVE_ARC4RANDOM
18 static bool seeded = false;
19 #endif
20
21
22 int
23 m_rand (unsigned char *buf, size_t n) {
24 #if !HAVE_ARC4RANDOM
25 if (! seeded) {
26 FILE *devurandom;
27 unsigned int seed;
28
29 if ((devurandom = fopen ("/dev/urandom", "r"))) {
30 if (fread (&seed, sizeof (seed), 1, devurandom) == 1)
31 seeded = true;
32 fclose (devurandom);
33 }
34
35 if (! seeded) {
36 /* This seed calculation is from Helmut G. Katzgraber, "Random
37 Numbers in Scientific Computing: An Introduction",
38 arXiv:1005.4117v1 [physics.comp-ph], 22 May 2010, p. 19.
39 time() and getpid() shouldn't fail on POSIX platforms. */
40 seed = abs ((int) ((time (0) * 181 * ((getpid ()-83) * 359)) % 104729));
41 seeded = true;
42 }
43
44 srand (seed);
45 }
46
47 while (n > 0) {
48 int rnd = rand ();
49 unsigned char *rndp = (unsigned char *) &rnd;
50 unsigned int i;
51
52 for (i = 0; i < sizeof rnd && n > 0; ++i, --n) {
53 *buf++ = *rndp++;
54 }
55 }
56 #else
57 arc4random_buf(buf, n);
58 #endif
59
60 return 0;
61 }