blob: 4d2e51cf87410a7ebb43a08e431dd2a1e86ad263 (
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
|
/**
* RDRAND RNG
* (C) 2016 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 {
RDRAND_RNG::RDRAND_RNG()
{
if(!CPUID::has_rdrand())
throw Exception("Current CPU does not support RDRAND instruction");
}
//static
uint32_t RDRAND_RNG::rdrand()
{
bool ok = false;
uint32_t r = rdrand_status(ok);
while(!ok)
{
r = rdrand_status(ok);
}
return r;
}
//static
uint32_t RDRAND_RNG::rdrand_status(bool& ok)
{
ok = false;
uint32_t r = 0;
for(size_t i = 0; i != BOTAN_ENTROPY_RDRAND_RETRIES; ++i)
{
#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)
{
ok = true;
return r;
}
}
return 0;
}
void RDRAND_RNG::randomize(uint8_t out[], size_t out_len)
{
while(out_len >= 4)
{
uint32_t r = RDRAND_RNG::rdrand();
store_le(r, out);
out += 4;
out_len -= 4;
}
if(out_len) // between 1 and 3 trailing bytes
{
uint32_t r = RDRAND_RNG::rdrand();
for(size_t i = 0; i != out_len; ++i)
out[i] = get_byte(i, r);
}
}
}
|