File: randombytes.c

package info (click to toggle)
dq 20161210-1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 1,644 kB
  • ctags: 1,195
  • sloc: ansic: 9,367; sh: 418; python: 77; makefile: 18
file content (36 lines) | stat: -rw-r--r-- 656 bytes parent folder | download
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
/* taken from nacl-20110221, from randombytes/devurandom.c (public domain) */
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "randombytes.h"

/* it's really stupid that there isn't a syscall for this */

static int fd = -1;

void randombytes(unsigned char *x,unsigned long long xlen)
{
  int i;

  if (fd == -1) {
    for (;;) {
      fd = open("/dev/urandom",O_RDONLY);
      if (fd != -1) break;
      sleep(1);
    }
  }

  while (xlen > 0) {
    if (xlen < 1048576) i = xlen; else i = 1048576;

    i = read(fd,x,i);
    if (i < 1) {
      sleep(1);
      continue;
    }

    x += i;
    xlen -= i;
  }
}