Botan 2.1.0 Crypto and TLS for C++11

- Main Page
- Namespaces
- Classes
- Files

- File List
- File Members

rdrand_rng.cpp
Go to the documentation of this file.
1 /*
2 * RDRAND RNG
3 * (C) 2016 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7
8 #include <botan/rdrand_rng.h>
9 #include <botan/loadstor.h>
10 #include <botan/cpuid.h>
11
12 #if !defined(BOTAN_USE_GCC_INLINE_ASM)
13 #include <immintrin.h>
14 #endif
15
16 namespace Botan {
17
18 RDRAND_RNG::RDRAND_RNG()
19 {
20 if(!CPUID::has_rdrand())
21 throw Exception("Current CPU does not support RDRAND instruction");
22 }
23
24 //static
25 uint32_t RDRAND_RNG::rdrand()
26 {
27 bool ok = false;
28 uint32_t r = rdrand_status(ok);
29
30 while(!ok)
31 {
32 r = rdrand_status(ok);
33 }
34
35 return r;
36 }
37
38 //static
39 BOTAN_FUNC_ISA("rdrnd")
40 uint32_t RDRAND_RNG::rdrand_status(bool& ok)
41 {
42 ok = false;
43 uint32_t r = 0;
44
45 for(size_t i = 0; i != BOTAN_ENTROPY_RDRAND_RETRIES; ++i)
46 {
47 #if defined(BOTAN_USE_GCC_INLINE_ASM)
48 int cf = 0;
49
50 // Encoding of rdrand %eax
51 asm(".byte 0x0F, 0xC7, 0xF0; adcl $0,%1" :
52 "=a" (r), "=r" (cf) : "0" (r), "1" (cf) : "cc");
53 #else
54 int cf = _rdrand32_step(&r);
55 #endif
56 if(1 == cf)
57 {
58 ok = true;
59 return r;
60 }
61 }
62
63 return 0;
64 }
65
66 void RDRAND_RNG::randomize(uint8_t out[], size_t out_len)
67 {
68 while(out_len >= 4)
69 {
70 uint32_t r = RDRAND_RNG::rdrand();
71
72 store_le(r, out);
73 out += 4;
74 out_len -= 4;
75 }
76
77 if(out_len) // between 1 and 3 trailing bytes
78 {
79 uint32_t r = RDRAND_RNG::rdrand();
80 for(size_t i = 0; i != out_len; ++i)
81 out[i] = get_byte(i, r);
82 }
83 }
84
85 }
Botan::Exception
Definition: exceptn.h:21
Botan::RDRAND_RNG::randomize
void randomize(uint8_t out[], size_t out_len) override
Definition: rdrand_rng.cpp:66
Botan::RDRAND_RNG
Definition: rdrand_rng.h:15
Botan::RDRAND_RNG::rdrand_status
static uint32_t rdrand_status(bool &ok)
Definition: rdrand_rng.cpp:40
BOTAN_FUNC_ISA
#define BOTAN_FUNC_ISA(isa)
Definition: compiler.h:48
Botan
Definition: alg_id.cpp:13
Botan::RDRAND_RNG::rdrand
static uint32_t rdrand()
Definition: rdrand_rng.cpp:25
Botan::get_byte
uint8_t get_byte(size_t byte_num, T input)
Definition: loadstor.h:47
Botan::RDRAND_RNG::RDRAND_RNG
RDRAND_RNG()
Definition: rdrand_rng.cpp:18
Botan::store_le
void store_le(uint16_t in, uint8_t out[2])
Definition: loadstor.h:457