platform-specific.inc 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */
  2. #ifndef _UECC_PLATFORM_SPECIFIC_H_
  3. #define _UECC_PLATFORM_SPECIFIC_H_
  4. #include "types.h"
  5. #if (defined(_WIN32) || defined(_WIN64))
  6. /* Windows */
  7. // use pragma syntax to prevent tweaking the linker script for getting CryptXYZ function
  8. #pragma comment(lib, "crypt32.lib")
  9. #pragma comment(lib, "advapi32.lib")
  10. #define WIN32_LEAN_AND_MEAN
  11. #include <windows.h>
  12. #include <wincrypt.h>
  13. static int default_RNG(uint8_t *dest, unsigned size) {
  14. HCRYPTPROV prov;
  15. if (!CryptAcquireContext(&prov, NULL, NULL, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT)) {
  16. return 0;
  17. }
  18. CryptGenRandom(prov, size, (BYTE *)dest);
  19. CryptReleaseContext(prov, 0);
  20. return 1;
  21. }
  22. #define default_RNG_defined 1
  23. #elif defined(unix) || defined(__linux__) || defined(__unix__) || defined(__unix) || \
  24. (defined(__APPLE__) && defined(__MACH__)) || defined(uECC_POSIX)
  25. /* Some POSIX-like system with /dev/urandom or /dev/random. */
  26. #include <sys/types.h>
  27. #include <fcntl.h>
  28. #include <unistd.h>
  29. #ifndef O_CLOEXEC
  30. #define O_CLOEXEC 0
  31. #endif
  32. static int default_RNG(uint8_t *dest, unsigned size) {
  33. int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);
  34. if (fd == -1) {
  35. fd = open("/dev/random", O_RDONLY | O_CLOEXEC);
  36. if (fd == -1) {
  37. return 0;
  38. }
  39. }
  40. char *ptr = (char *)dest;
  41. size_t left = size;
  42. while (left > 0) {
  43. ssize_t bytes_read = read(fd, ptr, left);
  44. if (bytes_read <= 0) { // read failed
  45. close(fd);
  46. return 0;
  47. }
  48. left -= bytes_read;
  49. ptr += bytes_read;
  50. }
  51. close(fd);
  52. return 1;
  53. }
  54. #define default_RNG_defined 1
  55. #endif /* platform */
  56. #endif /* _UECC_PLATFORM_SPECIFIC_H_ */