Botan  2.1.0
Crypto and TLS for C++11
es_capi.cpp
Go to the documentation of this file.
1 /*
2 * Win32 CryptoAPI EntropySource
3 * (C) 1999-2009,2016 Jack Lloyd
4 *
5 * Botan is released under the Simplified BSD License (see license.txt)
6 */
7 
8 #include <botan/internal/es_capi.h>
9 #include <botan/parsing.h>
10 #define NOMINMAX 1
11 #include <windows.h>
12 #include <wincrypt.h>
13 
14 namespace Botan {
15 
16 namespace {
17 
18 class CSP_Handle_Impl : public Win32_CAPI_EntropySource::CSP_Handle
19  {
20  public:
21  explicit CSP_Handle_Impl(uint64_t capi_provider)
22  {
23  m_valid = ::CryptAcquireContext(&m_handle,
24  0,
25  0,
26  static_cast<DWORD>(capi_provider),
27  CRYPT_VERIFYCONTEXT);
28  }
29 
30  ~CSP_Handle_Impl()
31  {
32  if(m_valid)
33  ::CryptReleaseContext(m_handle, 0);
34  }
35 
36  size_t gen_random(uint8_t out[], size_t n) const
37  {
38  if(m_valid && ::CryptGenRandom(m_handle, static_cast<DWORD>(n), out))
39  return n;
40  return 0;
41  }
42 
43  private:
44  bool m_valid;
45  HCRYPTPROV m_handle;
46  };
47 
48 }
49 
50 /*
51 * Gather Entropy from Win32 CAPI
52 */
54  {
55  secure_vector<uint8_t> buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);
56  size_t bits = 0;
57 
58  for(size_t i = 0; i != m_csp_provs.size(); ++i)
59  {
60  size_t got = m_csp_provs[i]->gen_random(buf.data(), buf.size());
61 
62  if(got > 0)
63  {
64  rng.add_entropy(buf.data(), got);
65  bits += got * 8;
66  }
67  }
68 
69  return bits;
70  }
71 
72 /*
73 * Win32_Capi_Entropysource Constructor
74 */
76  {
77  for(std::string prov_name : split_on(provs, ':'))
78  {
79  DWORD prov_type;
80 
81  if(prov_name == "RSA_FULL")
82  prov_type = PROV_RSA_FULL;
83  else if(prov_name == "INTEL_SEC")
84  prov_type = PROV_INTEL_SEC;
85  else if(prov_name == "RNG")
86  prov_type = PROV_RNG;
87  else
88  continue;
89 
90  m_csp_provs.push_back(std::unique_ptr<CSP_Handle>(new CSP_Handle_Impl(prov_type)));
91  }
92  }
93 
94 }
bool m_valid
Definition: es_capi.cpp:44
virtual void add_entropy(const uint8_t input[], size_t length)=0
size_t poll(RandomNumberGenerator &rng) override
Definition: es_capi.cpp:53
std::vector< std::string > split_on(const std::string &str, char delim)
Definition: parsing.cpp:138
HCRYPTPROV m_handle
Definition: es_capi.cpp:45
std::vector< T, secure_allocator< T >> secure_vector
Definition: secmem.h:121
Win32_CAPI_EntropySource(const std::string &provs="")
Definition: es_capi.cpp:75
Definition: alg_id.cpp:13