devurandom.c 650 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. #include <sys/types.h>
  2. #include <sys/stat.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. /* it's really stupid that there isn't a syscall for this */
  6. static int fd = -1;
  7. void randombytes(unsigned char *x,unsigned long long xlen)
  8. {
  9. int i;
  10. if (fd == -1) {
  11. for (;;) {
  12. fd = open("/dev/urandom",O_RDONLY);
  13. if (fd != -1) break;
  14. sleep(1);
  15. }
  16. }
  17. while (xlen > 0) {
  18. if (xlen < 1048576) i = xlen; else i = 1048576;
  19. i = read(fd,x,i);
  20. if (i < 1) {
  21. sleep(1);
  22. continue;
  23. }
  24. x += i;
  25. xlen -= i;
  26. }
  27. }
  28. int random()
  29. {
  30. int out;
  31. randombytes((unsigned char*) &out, sizeof(int));
  32. return out;
  33. }