linux_glue.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /*
  2. Copyright (c) 2023 Bruce A Henderson
  3. This software is provided 'as-is', without any express or implied
  4. warranty. In no event will the authors be held liable for any damages
  5. arising from the use of this software.
  6. Permission is granted to anyone to use this software for any purpose,
  7. including commercial applications, and to alter it and redistribute it
  8. freely, subject to the following restrictions:
  9. 1. The origin of this software must not be misrepresented; you must not
  10. claim that you wrote the original software. If you use this software
  11. in a product, an acknowledgment in the product documentation would be
  12. appreciated but is not required.
  13. 2. Altered source versions must be plainly marked as such, and must not be
  14. misrepresented as being the original software.
  15. 3. This notice may not be removed or altered from any source
  16. distribution.
  17. */
  18. #include <stdlib.h>
  19. #include <fcntl.h>
  20. #include <unistd.h>
  21. #include <stdint.h>
  22. static inline double uint64_to_double(uint64_t v) {
  23. return (v >> 11) * (1.0/9007199254740992.0);
  24. }
  25. int bmx_secure_init() {
  26. return open("/dev/urandom", O_RDONLY);
  27. }
  28. void bmx_secure_destroy(int fd) {
  29. close(fd);
  30. }
  31. uint64_t bmx_secure_random(int fd) {
  32. uint64_t result;
  33. read(fd, &result, sizeof(result));
  34. return result;
  35. }
  36. double bmx_secure_next_double(int fd) {
  37. return uint64_to_double(bmx_secure_random(fd));
  38. }