open-license-manager
2014-08-05 82d408374c8ece8f13b50b93ff24ab9633de14f0
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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
 
#define _WIN32_WINNT 0x0400
#include <windows.h>
#include <wincrypt.h>
#include <tchar.h>
 
// Helper class definition to generate and export Public/Private keys
// for Asymmetric encryption. The semantics for usage are:
// Call AcquireContext with a container name, call
// GenerateKeyPair next and then  call ExportPublicKey or
// ExportPrivateKey.
class CryptoHelper
{
private:
       HCRYPTPROV    m_hCryptProv;
public:
       HCRYPTKEY     m_hCryptKey;
       CryptoHelper();
       ~CryptoHelper();
       HRESULT AcquireContext(LPCTSTR wszContainerName);
       HRESULT GenerateKeyPair();
 
       HRESULT ExportPublicKey(BYTE **ppPublicKey, DWORD &cbKeySize);;
       HRESULT ExportPrivateKey(BYTE **ppPrivateKey, DWORD &cbKeySize);
};
3333333//--------------------------------------------------------------------
// The destructor releases the handles acquired
// when an object goes out of scope.
//--------------------------------------------------------------------
CryptoHelper::~CryptoHelper()
{
       if (m_hCryptProv)
       {
              CryptReleaseContext(m_hCryptProv,0);
              m_hCryptProv = NULL;
       }
       if (m_hCryptKey)
              m_hCryptKey = NULL;
}
 
//--------------------------------------------------------------------
// This method calls the CryptAcquireContext function
// to get a handle to a key container owned by the the
// Microsoft Enhanced Cryptographic Provider.
//--------------------------------------------------------------------
HRESULT CryptoHelper::AcquireContext(LPCTSTR wszContainerName)
{
       HRESULT       hr = S_OK;
       DWORD         dwErrCode;
// Release a previously acquired handle to the key container.
if (m_hCryptProv != NULL)
       {
              CryptReleaseContext(m_hCryptProv,0);
              m_hCryptProv = NULL;
       }
// Release a previously acquired handle to key-pair.
       if (m_hCryptKey != NULL)
              m_hCryptKey = NULL;
       // Attempt to acquire a context and a key container.
// The context will use Microsoft Enhanced Cryptographic
       // Provider for the RSA_FULL provider type.
       if(!CryptAcquireContext(&m_hCryptProv,
                               wszContainerName,
                               MS_ENHANCED_PROV,
                               PROV_RSA_FULL,
    CRYPT_MACHINE_KEYSET))
       {
         // An error occurred in acquiring the context. This could mean
         // that the key container requested does not exist. In this case,
        // the function can be called again to attempt to create a new key
              // container.
              if (GetLastError() == NTE_BAD_KEYSET)
              {
                     if(!CryptAcquireContext(&m_hCryptProv,
                                            wszContainerName,
                                            MS_ENHANCED_PROV,   PROV_RSA_FULL,
                                            CRYPT_MACHINE_KEYSET|CRYPT_NEWKEYSET))
                     {
                           dwErrCode = GetLastError();
                            return HRESULT_FROM_WIN32(dwErrCode);
                     }
              }
              else
              {
                     dwErrCode = GetLastError();
                     return HRESULT_FROM_WIN32(dwErrCode);
              }
       }
       return hr;
}
//--------------------------------------------------------------------
 
// This method calls the CryptGenKey function to get a handle to an
 
// exportable key-pair. The key-pair is  generated with the RSA public-key
// key exchange algorithm using Microsoft Enhanced Cryptographic Provider.
//--------------------------------------------------------------------
HRESULT CryptoHelper::GenerateKeyPair()
{
       HRESULT       hr = S_OK;
       DWORD         dwErrCode;
       // If the handle to key container is NULL, fail.
if (m_hCryptProv == NULL)
              return E_FAIL;
// Release a previously acquired handle to key-pair.
if (m_hCryptKey)
              m_hCryptKey = NULL;
       // Call the CryptGenKey method to get a handle
       // to a new exportable key-pair.
if(!CryptGenKey(m_hCryptProv,
                ENCRYPT_ALGORITHM,
   KEYLENGTH | CRYPT_EXPORTABLE,
   &m_hCryptKey))
       {
              dwErrCode = GetLastError();
              return HRESULT_FROM_WIN32(dwErrCode);
       }
       return hr;
}
//--------------------------------------------------------------------
// This method calls the CryptExportKey function to get the Public key
// in a byte array. The byte array is allocated on the heap and the size
// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
//--------------------------------------------------------------------
HRESULT CryptoHelper::ExportPublicKey(BYTE **ppPublicKey, DWORD &cbKeySize)
{
       HRESULT hr = S_OK;
       DWORD    dwErrCode;
       DWORD dwBlobLen;
       BYTE *pbKeyBlob = NULL;
       // If the handle to key container is NULL, fail.
       if (m_hCryptKey == NULL)
              return E_FAIL;
       // This call here determines the length of the key
       // blob.
       if(!CryptExportKey(
                 m_hCryptKey,
                 NULL,
                 PUBLICKEYBLOB,
                 0,
                 NULL,
                 &dwBlobLen))
       {
              dwErrCode = GetLastError();
              return HRESULT_FROM_WIN32(dwErrCode);
       }
       // Allocate memory for the pbKeyBlob.
       if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
       {
              return E_OUTOFMEMORY;
       }
       // Do the actual exporting into the key BLOB.
       if(!CryptExportKey(
                 m_hCryptKey,
                 NULL,
                 PUBLICKEYBLOB,
                 0,
                 pbKeyBlob,
                 &dwBlobLen))
       {
              delete pbKeyBlob;
              dwErrCode = GetLastError();
              return HRESULT_FROM_WIN32(dwErrCode);
       }
       else
       {
               *ppPublicKey = pbKeyBlob;
               cbKeySize = dwBlobLen;
       }
       return hr;
}
//--------------------------------------------------------------------
// This method calls the CryptExportKey function to get the Private key
// in a byte array. The byte array is allocated on the heap and the size
// of this is returned to the caller. The caller is responsible for releasing // this memory using a delete call.
//--------------------------------------------------------------------
HRESULT CryptoHelper::ExportPrivateKey(BYTE **ppPrivateKey, DWORD &cbKeySize)
{
       HRESULT       hr = S_OK;
       DWORD         dwErrCode;
       DWORD dwBlobLen;
       BYTE *pbKeyBlob;
       // If the handle to key container is NULL, fail.
       if (m_hCryptKey == NULL)
              return E_FAIL;
       // This call here determines the length of the key
       // blob.
       if(!CryptExportKey(
                 m_hCryptKey,
                 NULL,
                 PRIVATEKEYBLOB,
                 0,
                 NULL,
                 &dwBlobLen))
       {
              dwErrCode = GetLastError();
              return HRESULT_FROM_WIN32(dwErrCode);
       }
       // Allocate memory for the pbKeyBlob.
       if((pbKeyBlob = new BYTE[dwBlobLen]) == NULL)
       {
              return E_OUTOFMEMORY;
       }
 
       // Do the actual exporting into the key BLOB.
       if(!CryptExportKey(
                 m_hCryptKey,
                 NULL,
                 PRIVATEKEYBLOB,
                 0,
                 pbKeyBlob,
                 &dwBlobLen))
       {
              delete pbKeyBlob;
              dwErrCode = GetLastError();
              return HRESULT_FROM_WIN32(dwErrCode);
       }
       else
       {
               *ppPrivateKey = pbKeyBlob;
               cbKeySize = dwBlobLen;
       }
       return hr;
}
 
Main.cpp
 #include <stdio.h>
#include "CryptoHelper.h"
void main()
{
       CryptoHelper  cryptoHlpr;
       BYTE          *pbPublicKey = NULL, *pbPrivateKey = NULL;
       DWORD         dwPublicKeySize = 0,dwPrivateKeySize = 0;
       HRESULT       hr = S_OK;
       // Get the key container context.
       if (FAILED(hr = cryptoHlpr.AcquireContext((L"TestContainer"))))
       {
// Call FormatMessage to display the error returned in hr.
              return;
       }
        // Generate the public/private key pair.
if (FAILED(hr = cryptoHlpr.GenerateKeyPair()))
       {
// Call FormatMessage to display the error returned in hr.
              return;
       }
       // Export out the public key blob.
if (FAILED(hr = cryptoHlpr.ExportPublicKey(&pbPublicKey, dwPublicKeySize)))
       {
// Call FormatMessage to display the error returned in hr.
              return;
       }
       // Print out the public key to console as a
       // hexadecimal string.
wprintf(L"\n\nPublicKey = \"");
       for (DWORD i=0; i < dwPublicKeySize; i++)
       {
              wprintf(L"%02x",pbPublicKey[i]);
       }
       wprintf(L"\"\n");
       // Export out the private key blob.
       cryptoHlpr.ExportPrivateKey(&pbPrivateKey, dwPrivateKeySize);
       // Print out the private key to console as a
       // hexadecimal string.
       wprintf(L"\n\nPrivateKey = \"");
       for (i=0; i < dwPrivateKeySize; i++)
       {
              wprintf(L"%02x",pbPrivateKey[i]);
       }
wprintf(L"\"\n");
       // Delete the public key blob allocated by the
// ExportPublicKey method.
if (pbPublicKey)
          delete [] pbPublicKey;
       // Delete the private key blob allocated by the
// ExportPrivateKey method.
       if (pbPrivateKey)
              delete [] pbPrivateKey;
       return;
}