-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBCryptWrap.hpp
365 lines (288 loc) · 8.36 KB
/
BCryptWrap.hpp
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#pragma once
#include <windows.h>
#include <bcrypt.h>
#include <map>
#include <string>
#include <vector>
#pragma comment(lib, "bcrypt")
namespace nk125 {
typedef std::vector<unsigned char> bytes;
// BCrypt Wrapper Class
class BCryptWC {
public:
/*
This structure is very simple
bitsize is the bits length you want for the password (128 for AES in example)
Name, this is the internal bcrypt algorithm name, for example BCRYPT_DES_ALGORITHM
*/
struct CipherAlgorithm {
int bitsize;
std::wstring Name;
CipherAlgorithm(std::wstring a, int b) {
bitsize = b;
Name = a;
}
CipherAlgorithm() {
bitsize = 0;
Name = L"NULL";
}
};
private:
BCRYPT_ALG_HANDLE BCAh;
bytes genBuf;
int bits = 0;
bool storeKey = true;
struct Key {
BCRYPT_KEY_HANDLE Handle;
bytes alloc;
};
Key kIObj;
inline bool NT_SUCCESS(NTSTATUS x) {
return x >= 0;
}
bool wcmp(std::wstring a, std::wstring b) {
return a.find(b) != std::wstring::npos;
}
std::map<int, CipherAlgorithm> cipherList{
{AES128, CipherAlgorithm(BCRYPT_AES_ALGORITHM, 128)},
{AES192, CipherAlgorithm(BCRYPT_AES_ALGORITHM, 192)},
{AES256, CipherAlgorithm(BCRYPT_AES_ALGORITHM, 256)},
};
void openAlgorithm(std::wstring name, int bitsz) {
if (BCryptOpenAlgorithmProvider(&BCAh, name.c_str(), NULL, 0) != 0) {
throw Exception("Failed to open algorithm");
}
else {
bits = bitsz;
}
}
public:
/*
Anonymous enum with the default algorithms and their required key bits length
You can access to this enum with the class object or the static way
nk125::BCryptWC::AES128
OR
myBCryptWC.AES128
*/
enum {
AES128 = 0,
AES192,
AES256
};
/*
Global BCryptWC Exception class
*/
class Exception {
private:
std::string s;
public:
Exception(const char* c) {
s.assign(c);
}
Exception(std::string w) {
s = w;
}
Exception() {
s = "Unknown Error";
}
const char* what() noexcept {
return s.c_str();
}
};
BCryptWC() {
kIObj.Handle = NULL;
BCAh = NULL;
}
/*
Encrypts data with previously initialized password
@param nk125::bytes = Plaintext
@param bool = in-place Encryption?
@return bytes = ciphertext, if valid (else returns plaintext)
*/
bytes encrypt(bytes& data, bool inPlace = false) {
ULONG dsz = static_cast<ULONG>(data.size());
ULONG esz;
if (!NT_SUCCESS(BCryptEncrypt(kIObj.Handle, &data[0], dsz, NULL, NULL, 0, NULL, 0, &esz, BCRYPT_BLOCK_PADDING))) {
throw Exception("Failed to get encrypted size");
return data;
}
genBuf.resize(esz);
PBYTE ptr = &genBuf[0];
if (inPlace) {
data.resize(esz);
ptr = &data[0];
genBuf.clear();
}
if (!NT_SUCCESS(BCryptEncrypt(kIObj.Handle, &data[0], dsz, NULL, NULL, 0, ptr, esz, &dsz, BCRYPT_BLOCK_PADDING))) {
throw Exception("Failed to encrypt data");
return data;
}
return genBuf;
}
/*
Decrypts data with previously initialized password
@param nk125::bytes = Ciphertext
@param bool = in-place Encryption?
@return bytes = plaintext, if valid (else returns ciphertext)
*/
bytes decrypt(bytes& data, bool inPlace = false) {
ULONG esz = static_cast<ULONG>(data.size());
ULONG psz;
if (!NT_SUCCESS(BCryptDecrypt(kIObj.Handle, &data[0], esz, NULL, NULL, 0, NULL, 0, &psz, BCRYPT_BLOCK_PADDING))) {
throw Exception("Failed to get encrypted size");
return data;
}
genBuf.resize(esz);
PBYTE ptr = &genBuf[0];
if (inPlace) {
data.resize(esz);
ptr = &data[0];
genBuf.clear();
}
if (!NT_SUCCESS(BCryptDecrypt(kIObj.Handle, &data[0], esz, NULL, NULL, 0, ptr, psz, &psz, BCRYPT_BLOCK_PADDING))) {
throw Exception("Failed to encrypt data");
return data;
}
(inPlace ? data : genBuf).resize(psz);
return genBuf;
}
/*
The password is actually storaged by BCrypt, but if you don't want the password inside
the process memory space, call this
@param None
@return None
*/
void preventKeyStorage() {
storeKey = false;
kIObj.alloc.clear();
}
/*
Exports the password storaged in the process memory space
@param None
@return nk125::bytes = unsigned char key
*/
bytes exportKey() {
return kIObj.alloc;
}
/*
Validates and imports password
@param nk125::bytes = unsigned char key
@return None
*/
void importKey(bytes& key) {
ULONG sz = static_cast<ULONG>(key.size());
if (!NT_SUCCESS(BCryptGenerateSymmetricKey(BCAh, &kIObj.Handle, NULL, 0, &key[0], sz, 0))) {
throw Exception("Failed to generate symmetric key (probably invalid bit/key size)");
return;
}
if (!NT_SUCCESS(BCryptSetProperty(kIObj.Handle, BCRYPT_CHAINING_MODE, (PBYTE)BCRYPT_CHAIN_MODE_ECB, sizeof(BCRYPT_CHAIN_MODE_ECB), 0))) {
throw Exception("Failed to set Chaining Mode (ECB)");
return;
}
if (storeKey) {
kIObj.alloc = key;
}
}
/*
Generates a key complaining the bit size
Stores the key in an internal bcrypt key handle and optionally in the process memory space
@param None
@return None
*/
void genKey() {
if (!bits) bits = 128;
int byteSz = bits / 8;
genBuf.resize(byteSz);
if (!NT_SUCCESS(BCryptGenRandom(NULL, &genBuf[0], byteSz, BCRYPT_USE_SYSTEM_PREFERRED_RNG))) {
throw Exception("Failed to generate random bytes");
return;
}
importKey(genBuf);
genBuf.clear();
}
/*
Only adds an user-provided algorithm in the cipher algorithm list
==========================================
To ubicate the cipher algorithm in init(), you need to add the relative index to the last element in
the anonymous enum (AES256)
==========================================
This function is more preferred than initOSR() because you can discern before key import/generation
if the algorithm is actually supported by bcrypt (when you call init)
==========================================
Example:
The algorithm need to support ECB chaining mode to add a key to it
byteObf.registerNewAlgorithm(BCryptWC::CipherAlgorithm(BCRYPT_3DES_ALGORITHM, 168));
byteObf.init(AES256 + 1);
byteObf.registerNewAlgorithm(BCryptWC::CipherAlgorithm(BCRYPT_DES_ALGORITHM, 56));
byteObf.init(AES256 + 2);
*/
// ==========================================
/*
Register a new user-provided algorithm
@param nk125::BCryptWC::CipherAlgorithm = Algorithm to register
@return None
*/
void registerNewAlgorithm(CipherAlgorithm cA) {
int id = cipherList.rbegin()->first + 1;
cipherList[id] = cA;
return;
}
/*
init() but doesn't check if it's in the registered algorithms by OS
(init Override System Restrictions)
@param nk125::BCryptWC::CipherAlgorithm = Algorithm to open
@return None
*/
void initOSR(CipherAlgorithm cA) {
try {
openAlgorithm(cA.Name, cA.bitsize);
}
catch (Exception& e) {
throw e;
}
}
/*
Initialize internal bcrypt algorithm handle
@param int = Type of algorithm, can be one of the default algorithms or a custom one
@return None
*/
void init(int type = 0) {
if (type < AES128 || type >= cipherList.size()) {
throw Exception("Invalid Type");
return;
}
bool found = false;
ULONG cn = 0;
BCRYPT_ALGORITHM_IDENTIFIER* bai[1024];
ZeroMemory(bai, sizeof(bai));
if (NT_SUCCESS(BCryptEnumAlgorithms(BCRYPT_CIPHER_OPERATION, &cn, bai, 0))) {
std::wstring name = cipherList[type].Name;
for (DWORD i = 0; i < cn; i++) {
BCRYPT_ALGORITHM_IDENTIFIER* alg = std::move(bai[i]);
if (alg == NULL) continue;
std::wstring algname = alg->pszName;
BCryptFreeBuffer(alg);
if (wcmp(algname, name)) {
found = true;
try {
openAlgorithm(algname, cipherList[type].bitsize);
break;
}
catch (Exception& e) {
throw e;
}
}
}
}
else {
throw Exception("Internal BCrypt Error");
}
if (!found) throw Exception("Algorithm not found");
return;
}
~BCryptWC() {
if (kIObj.Handle) BCryptDestroyKey(kIObj.Handle);
if (BCAh) BCryptCloseAlgorithmProvider(BCAh, 0);
}
};
}