aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/entropy/cryptoapi_rng/es_capi.cpp
blob: 3d744245ef7e340a80e07ea56f9e5a62a35e6cc6 (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
/*
* Win32 CryptoAPI EntropySource
* (C) 1999-2009,2016 Jack Lloyd
*
* Botan is released under the Simplified BSD License (see license.txt)
*/

#include <botan/internal/es_capi.h>
#include <botan/parsing.h>
#define NOMINMAX 1
#define _WINSOCKAPI_ // stop windows.h including winsock.h
#include <windows.h>
#include <wincrypt.h>

namespace Botan {

namespace {

class CSP_Handle_Impl : public Win32_CAPI_EntropySource::CSP_Handle
   {
   public:
      explicit CSP_Handle_Impl(uint64_t capi_provider)
         {
         m_valid = ::CryptAcquireContext(&m_handle,
                                         0,
                                         0,
                                         static_cast<DWORD>(capi_provider),
                                         CRYPT_VERIFYCONTEXT);
         }

      ~CSP_Handle_Impl()
         {
         if(m_valid)
            ::CryptReleaseContext(m_handle, 0);
         }

      size_t gen_random(uint8_t out[], size_t n) const
         {
         if(m_valid && ::CryptGenRandom(m_handle, static_cast<DWORD>(n), out))
            return n;
         return 0;
         }

   private:
      bool m_valid;
      HCRYPTPROV m_handle;
   };

}

/*
* Gather Entropy from Win32 CAPI
*/
size_t Win32_CAPI_EntropySource::poll(RandomNumberGenerator& rng)
   {
   secure_vector<uint8_t> buf(BOTAN_SYSTEM_RNG_POLL_REQUEST);
   size_t bits = 0;

   for(size_t i = 0; i != m_csp_provs.size(); ++i)
      {
      size_t got = m_csp_provs[i]->gen_random(buf.data(), buf.size());

      if(got > 0)
         {
         rng.add_entropy(buf.data(), got);
         bits += got * 8;
         }
      }

   return bits;
   }

/*
* Win32_Capi_Entropysource Constructor
*/
Win32_CAPI_EntropySource::Win32_CAPI_EntropySource(const std::string& provs)
   {
   for(std::string prov_name : split_on(provs, ':'))
      {
      DWORD prov_type;

      if(prov_name == "RSA_FULL")
         prov_type = PROV_RSA_FULL;
      else if(prov_name == "INTEL_SEC")
         prov_type = PROV_INTEL_SEC;
      else if(prov_name == "RNG")
         prov_type = PROV_RNG;
      else
         continue;

      m_csp_provs.push_back(std::unique_ptr<CSP_Handle>(new CSP_Handle_Impl(prov_type)));
      }
   }

}