randombytes.cpp 615 B

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