devurandom.c 553 B

12345678910111213141516171819202122232425262728293031323334
  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. }