aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/entropy/rdrand/rdrand.cpp
blob: ef8c5882d6a25992a8d8c654a98073aa1067af32 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* Entropy Source Using Intel's rdrand instruction
* (C) 2012,2015 Jack Lloyd
* (C) 2015 Daniel Neus
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/rdrand.h>
#include <botan/cpuid.h>
#include <botan/build.h>

#if !defined(BOTAN_USE_GCC_INLINE_ASM)
#include <immintrin.h>
#endif

namespace Botan {

namespace {

/// @returns 0 if RdRand failed after @param max_retries otherwise the 32 bit random number generated by RdRand
uint32_t get_32bit_random(const uint32_t max_retries) {
   for(size_t i = 0; i != max_retries; ++i)
      {
      uint32_t r = 0;

#if defined(BOTAN_USE_GCC_INLINE_ASM)
      int cf = 0;

      // Encoding of rdrand %eax
      asm(".byte 0x0F, 0xC7, 0xF0; adcl $0,%1" :
      "=a" (r), "=r" (cf) : "0" (r), "1" (cf) : "cc");
#else
      int cf = _rdrand32_step(&r);
#endif
      if(1 == cf)
         {
         return r;
         }
      }
   return 0;
   }
}

void Intel_Rdrand::poll(Entropy_Accumulator& accum) {
   if(!CPUID::has_rdrand())
      return;

   for(size_t i = 0; i != BOTAN_ENTROPY_INTEL_RNG_POLLS; ++i)
      {
      uint32_t random = get_32bit_random(BOTAN_ENTROPY_RDRAND_RETRIES);
      if(random)
         {
         accum.add(random, BOTAN_ENTROPY_ESTIMATE_HARDWARE_RNG);
         }
      }
   }

}