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.

ottery_entropy_rdrand.c 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. /* Libottery by Nick Mathewson.
  2. This software has been dedicated to the public domain under the CC0
  3. public domain dedication.
  4. To the extent possible under law, the person who associated CC0 with
  5. libottery has waived all copyright and related or neighboring rights
  6. to libottery.
  7. You should have received a copy of the CC0 legalcode along with this
  8. work in doc/cc0.txt. If not, see
  9. <http://creativecommons.org/publicdomain/zero/1.0/>.
  10. */
  11. #if defined(i386) || \
  12. defined(__i386) || \
  13. defined(__x86_64) || \
  14. defined(__M_IX86) || \
  15. defined(_M_IX86) || \
  16. defined(__INTEL_COMPILER)
  17. extern int ottery_valgrind_;
  18. /** Helper: invoke the RDRAND instruction to get 4 random bytes in the output
  19. * value. Return 0 on success, and an error on failure. */
  20. static int
  21. rdrand(uint32_t *therand) {
  22. unsigned char status;
  23. __asm volatile(".byte 0x0F, 0xC7, 0xF0 ; setc %1"
  24. : "=a" (*therand), "=qm" (status));
  25. return (status)==1 ? 0 : OTTERY_ERR_INIT_STRONG_RNG;
  26. }
  27. /** Generate bytes using the Intel RDRAND instruction. */
  28. static int
  29. ottery_get_entropy_rdrand(const struct ottery_entropy_config *cfg,
  30. struct ottery_entropy_state *state,
  31. uint8_t *out, size_t outlen)
  32. {
  33. int err;
  34. uint32_t *up = (uint32_t *) out;
  35. (void) cfg;
  36. (void) state;
  37. if (! (ottery_get_cpu_capabilities_() & OTTERY_CPUCAP_RAND) || ottery_valgrind_)
  38. return OTTERY_ERR_INIT_STRONG_RNG;
  39. while (outlen >= 4) {
  40. if ((err = rdrand(up)))
  41. return err;
  42. up += 1;
  43. outlen -= 4;
  44. }
  45. if (outlen) {
  46. uint32_t tmp;
  47. if ((err = rdrand(&tmp)))
  48. return err;
  49. memcpy(up, &tmp, outlen);
  50. }
  51. return 0;
  52. }
  53. #define ENTROPY_SOURCE_RDRAND \
  54. { ottery_get_entropy_rdrand, SRC(RDRAND)|DOM(CPU)|FL(FAST)|FL(STRONG) }
  55. #endif