aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/rng/rdrand_rng/rdrand_rng.cpp
blob: ece3d9f39a5ad3f91626f5bf2065ed4d0af7d2d3 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/*
* RDRAND RNG
* (C) 2016,2019 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/rdrand_rng.h>
#include <botan/loadstor.h>
#include <botan/cpuid.h>

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

namespace Botan {

namespace {

#if defined(BOTAN_TARGET_ARCH_IS_X86_64)
   typedef uint64_t rdrand_output;
#else
   typedef uint32_t rdrand_output;
#endif

#if !defined(BOTAN_USE_GCC_INLINE_ASM)
BOTAN_FUNC_ISA("rdrnd")
#endif
rdrand_output read_rdrand()
   {
   /*
   * According to Intel, RDRAND is guaranteed to generate a random
   * number within 10 retries on a working CPU
   */
   const size_t RDRAND_RETRIES = 10;

   for(size_t i = 0; i < RDRAND_RETRIES; ++i)
      {
      rdrand_output r = 0;
      int cf = 0;

#if defined(BOTAN_USE_GCC_INLINE_ASM)
      // same asm seq works for 32 and 64 bit
      asm("rdrand %0; adcl $0,%1" :
          "=r" (r), "=r" (cf) : "0" (r), "1" (cf) : "cc");
#elif defined(BOTAN_TARGET_ARCH_IS_X86_64)
      cf = _rdrand64_step(&r);
#else
      cf = _rdrand32_step(&r);
#endif
      if(1 == cf)
         {
         return r;
         }
      }

   throw PRNG_Unseeded("RDRAND read failed");
   }

}

void RDRAND_RNG::randomize(uint8_t out[], size_t out_len)
   {
   while(out_len >= sizeof(rdrand_output))
      {
      const rdrand_output r = read_rdrand();
      store_le(r, out);
      out += sizeof(rdrand_output);
      out_len -= sizeof(rdrand_output);
      }

   if(out_len > 0) // at most sizeof(rdrand_output)-1
      {
      const rdrand_output r = read_rdrand();
      for(size_t i = 0; i != out_len; ++i)
         out[i] = get_byte(i, r);
      }
   }

RDRAND_RNG::RDRAND_RNG()
   {
   if(!RDRAND_RNG::available())
      throw Invalid_State("Current CPU does not support RDRAND instruction");
   }

//static
bool RDRAND_RNG::available()
   {
   return CPUID::has_rdrand();
   }

//static
uint32_t RDRAND_RNG::rdrand()
   {
   return static_cast<uint32_t>(read_rdrand());
   }

//static
BOTAN_FUNC_ISA("rdrnd")
uint32_t RDRAND_RNG::rdrand_status(bool& ok)
   {
   ok = false;

   try
      {
      const uint32_t r = static_cast<uint32_t>(read_rdrand());
      ok = true;
      return r;
      }
   catch(PRNG_Unseeded&) {}

   return 0;
   }

}