You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

43 lines
975 B

  1. /********************************************************************************************
  2. * Hardware-based random number generation function using /dev/urandom
  3. *********************************************************************************************/
  4. #include "random.h"
  5. #include <stdlib.h>
  6. #include <unistd.h>
  7. #include <fcntl.h>
  8. static int lock = -1;
  9. static __inline void delay(unsigned int count)
  10. {
  11. while (count--) {}
  12. }
  13. int randombytes(unsigned char* random_array, unsigned long long nbytes)
  14. { // Generation of "nbytes" of random values
  15. int r, n = (int)nbytes, count = 0;
  16. if (lock == -1) {
  17. do {
  18. lock = open("/dev/urandom", O_RDONLY);
  19. if (lock == -1) {
  20. delay(0xFFFFF);
  21. }
  22. } while (lock == -1);
  23. }
  24. while (n > 0) {
  25. do {
  26. r = read(lock, random_array+count, n);
  27. if (r == -1) {
  28. delay(0xFFFF);
  29. }
  30. } while (r == -1);
  31. count += r;
  32. n -= r;
  33. }
  34. return 0;
  35. }