-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkpabe.cpp
527 lines (450 loc) · 14 KB
/
kpabe.cpp
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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
#include <string>
#include <map>
#include <cmath>
#include <algorithm>
#include <numeric>
#include <functional>
#include <array>
#include <vector>
#include <mbedtls/cipher.h>
#include <mbedtls/md.h>
#include <pbc.h>
#include "kpabe.hpp"
//Debugging
#include <iostream>
using namespace std;
// For the encrypt/decrypt methods.
static const size_t AES_BLOCK_SIZE = 16;
static const size_t AES_KEY_SIZE = 32;
pairing_s pairing;
bool isInit = false;
pairing_ptr getPairing()
{
if (!isInit)
{
pairing_init_set_str(&pairing, TYPE_A_PARAMS.c_str());
isInit = true;
}
return &pairing;
}
void hashElement(element_t e, uint8_t *hashBuf)
{
const int elementSize = element_length_in_bytes(e);
uint8_t *elementBytes = new uint8_t[elementSize + 1];
element_to_bytes(elementBytes, e);
//TODO: use mbedtls_sha256
auto mdInfo = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
mbedtls_md(mdInfo, elementBytes, elementSize, hashBuf);
delete[] elementBytes;
}
/**
* Common interface to for symmetric encryption and decryption.
*
* Uses AES-256-CBC and zero-filled IV.
*/
void mbedtlsSymCrypt(const uint8_t *input, size_t ilen, uint8_t *key, uint8_t *output, size_t *olen, mbedtls_operation_t mode)
{
const auto cipherInfo = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_CBC);
mbedtls_cipher_context_t ctx;
mbedtls_cipher_setup(&ctx, cipherInfo);
mbedtls_cipher_setkey(&ctx, key, cipherInfo->key_bitlen, mode);
array<uint8_t, 16> iv;
iv.fill(0);
mbedtls_cipher_crypt(&ctx, iv.data(), cipherInfo->iv_size, input, ilen, output, olen);
}
void symEncrypt(const uint8_t *input, size_t ilen, uint8_t *key, uint8_t *output, size_t *olen)
{
mbedtlsSymCrypt(input, ilen, key, output, olen, MBEDTLS_ENCRYPT);
}
void symDecrypt(const uint8_t *input, size_t ilen, uint8_t *key, uint8_t *output, size_t *olen)
{
mbedtlsSymCrypt(input, ilen, key, output, olen, MBEDTLS_DECRYPT);
}
// Node
Node::Node(const Node &other)
{
attr = other.attr;
type = other.type;
children = other.children;
}
Node::Node(Node &&other) : attr(move(other.attr)),
type(other.type),
children(move(other.children))
{
}
Node::Node(int attr)
{
this->attr = attr;
}
Node::Node(Type type, const vector<Node> &children)
{
this->children = children;
this->type = type;
}
//Fixed Copy Assignment
Node &Node::operator=(const Node &other)
{
attr = other.attr;
type = other.type;
children = other.children;
}
//Move Assignment
Node &Node::operator=(Node &&other)
{
//assert(this != &other);
attr = move(other.attr);
type = move(other.type);
children = move(other.children);
return *this;
}
void Node::addChild(const Node &node)
{
children.push_back(node);
}
vector<int> Node::getLeafs() const
{
vector<int> attrs;
if (children.empty())
{
// Handles non-leaf node with one child
attrs.push_back(attr);
}
else
{
for (const Node &child : children)
{
if (child.children.empty())
{
attrs.push_back(child.attr);
}
else
{
auto childAttrs = child.getLeafs();
attrs.reserve(attrs.size() + childAttrs.size());
attrs.insert(attrs.end(), childAttrs.begin(), childAttrs.end());
}
}
}
return attrs;
}
unsigned int Node::getThreshold() const
{
return type == Type::OR ? 1 : static_cast<unsigned int>(children.size());
}
unsigned int Node::getPolyDegree() const
{
return getThreshold() - 1;
}
vector<element_s> Node::splitShares(element_s &rootSecret)
{
// Generate the coefficients for the polynomial.
auto threshold = getThreshold();
vector<element_s> coeff(threshold);
element_init_same_as(&coeff[0], &rootSecret);
element_set(&coeff[0], &rootSecret);
// Generate random coefficients, except for q(0), which is set to the rootSecret.
for (int i = 1; i <= getPolyDegree(); ++i)
{
element_init_same_as(&coeff[i], &rootSecret);
element_random(&coeff[i]);
}
// Calculate the shares for each child.
vector<element_s> shares(children.size());
element_t temp;
element_init_Zr(temp, getPairing());
// The scheme decription defines an ordering on the children in a node (index(x)).
// Here, we implicitly use a left to right order.
for (int x = 1; x <= children.size(); ++x)
{
auto share = &shares[x - 1];
element_init_same_as(share, &rootSecret);
element_set0(share);
// share = coeff[0] + coeff[1] * x + ... + coeff[threshold - 1] * x ^ (threshold - 1)
for (int power = 0; power < coeff.size(); ++power)
{
element_set_si(temp, pow(x, power)); //TODO: handle pow
element_mul(temp, temp, &coeff[power]);
element_add(share, share, temp);
}
}
element_clear(temp);
for (element_s &c : coeff)
{
element_clear(&c);
}
return shares;
} //splitShares
vector<element_s> Node::getSecretShares(element_s &rootSecret)
{
vector<element_s> shares;
if (children.empty())
{
shares.push_back(rootSecret);
}
else
{
auto childSplits = splitShares(rootSecret);
auto childSplitsIter = childSplits.begin();
for (Node &child : children)
{
auto childShares = child.getSecretShares(*childSplitsIter++);
shares.reserve(shares.size() + childShares.size());
shares.insert(shares.end(), childShares.begin(), childShares.end());
}
}
return shares;
}
vector<element_s> Node::recoverCoefficients()
{
auto threshold = getThreshold();
vector<element_s> coeff(threshold);
element_t iVal, jVal, temp;
element_init_Zr(iVal, getPairing());
element_init_Zr(jVal, getPairing());
element_init_Zr(temp, getPairing());
for (int i = 1; i <= threshold; ++i)
{
element_set_si(iVal, i);
element_s &result = coeff[i - 1];
element_init_Zr(&result, getPairing());
element_set1(&result);
for (int j = 1; j <= threshold; ++j)
{
if (i == j)
{
continue;
}
// result *= (0 - j) / (i - j)
element_set_si(jVal, -j);
element_add(temp, iVal, jVal);
element_div(temp, jVal, temp);
element_mul(&result, &result, temp);
}
}
element_clear(iVal);
element_clear(jVal);
element_clear(temp);
return coeff;
}
vector<pair<int, element_s>>
Node::satisfyingAttributes(const vector<int> &attributes,
element_s ¤tCoeff)
{
vector<pair<int, element_s>> sat;
if (children.empty())
{
if (find(attributes.begin(), attributes.end(), attr) != attributes.end())
{
sat.push_back({attr, currentCoeff});
}
}
else
{
auto recCoeffs = recoverCoefficients();
if (type == Type::AND)
{
bool allSatisfied = true;
vector<pair<int, element_s>> totalChildSat;
for (int i = 0; i < children.size(); ++i)
{
element_mul(&recCoeffs[i], &recCoeffs[i], ¤tCoeff);
auto childSat = children[i].satisfyingAttributes(attributes, recCoeffs[i]);
if (childSat.empty())
{
allSatisfied = false;
break;
}
totalChildSat.reserve(totalChildSat.size() + childSat.size());
totalChildSat.insert(totalChildSat.end(), childSat.begin(), childSat.end());
}
if (allSatisfied)
{
sat = totalChildSat;
}
}
else
{
auto &recCoeff0 = recCoeffs[0];
element_mul(&recCoeff0, &recCoeff0, ¤tCoeff);
for (auto &child : children)
{
// TODO: Optimization -
// Should return the shortest non-empty childSat instead of the first one.
auto childSat = child.satisfyingAttributes(attributes, recCoeff0);
if (!childSat.empty())
{
sat = childSat;
break;
}
}
}
}
return sat;
}
const vector<Node> &Node::getChildren() const
{
return children;
}
// DecryptionKey
DecryptionKey::DecryptionKey(const Node &policy) : accessPolicy(policy) {}
// Algorithm Setup
void setup(const vector<int> &attributes,
PublicParams &publicParams,
PrivateParams &privateParams)
{
element_init_Zr(&privateParams.mk, getPairing());
element_random(&privateParams.mk);
element_t g;
element_init_G1(g, getPairing());
element_random(g);
// Generate a random public and private element for each attribute
for (auto attr : attributes)
{
// private
element_s &si = privateParams.Si[attr];
element_init_Zr(&si, getPairing());
element_random(&si);
// public
element_s &Pi = publicParams.Pi[attr];
element_init_G1(&Pi, getPairing());
element_pow_zn(&Pi, g, &si);
}
element_init_G1(&publicParams.pk, getPairing());
element_pow_zn(&publicParams.pk, g, &privateParams.mk);
element_clear(g);
}
/**
* @brief An abstraction of createKey that allows different operation for hiding the
* secret shares.
*
* @param scramblingFunc A function that sets an element to the result of a function on
* a scambling key and a secret share. In the original paper the scrambling keys are
* the private keys and the function is division. The result of the scrambling is put
* in the first element, the shares in the second, the scramblng keys in the third.
* @type scramblingFunc function<void (element_t, element_t, element_t)>
*/
DecryptionKey _keyGeneration(element_s &rootSecret,
map<int, element_s> &scramblingKeys,
function<void(element_t, element_t, element_t)> scramblingFunc,
Node &accessPolicy)
{
auto leafs = accessPolicy.getLeafs();
auto shares = accessPolicy.getSecretShares(rootSecret);
DecryptionKey key(accessPolicy);
auto attrIter = leafs.begin();
auto sharesIter = shares.begin();
// The below is: Du[attr] = shares[attr] / attributeSecrets[attr]
for (; attrIter != leafs.end(); ++attrIter, ++sharesIter)
{
element_s &attrDi = key.Di[*attrIter];
element_init_Zr(&attrDi, getPairing());
scramblingFunc(&attrDi, &*sharesIter, &scramblingKeys[*attrIter]);
}
for (element_s &share : shares)
{
element_clear(&share);
}
return key;
}
DecryptionKey keyGeneration(PrivateParams &privateParams,
Node &accessPolicy)
{
return _keyGeneration(privateParams.mk, privateParams.Si, element_div, accessPolicy);
}
Cw_t createSecret(PublicParams ¶ms,
const vector<int> &attributes,
element_s &Cs)
{
element_t k;
element_init_Zr(k, getPairing());
element_random(k);
element_init_G1(&Cs, getPairing());
element_pow_zn(&Cs, ¶ms.pk, k);
Cw_t Cw;
for (auto attr : attributes)
{
element_s &i = Cw[attr];
element_init_G1(&i, getPairing());
element_pow_zn(&i, ¶ms.Pi[attr], k);
}
element_clear(k);
return Cw;
}
void recoverSecret(DecryptionKey &key,
Cw_t &Cw,
const vector<int> &attributes,
element_s &Cs)
{
// Get attributes that can satisfy the policy (and their coefficients).
element_t rootCoeff;
element_init_Zr(rootCoeff, getPairing());
element_set1(rootCoeff);
auto attrs = key.accessPolicy.satisfyingAttributes(attributes, *rootCoeff);
element_clear(rootCoeff);
if (attrs.empty())
{
throw UnsatError();
return;
}
element_t Zy;
element_init_G1(&Cs, getPairing());
element_init_G1(Zy, getPairing());
bool pastFirst = false; // Is this the first "part" of the product
// product = P(Ci ^ (Di * coeff(i)))
// NOTE: attrCoeffPair is modified
for (auto &attrCoeffPair : attrs)
{
element_mul(&attrCoeffPair.second, &key.Di[attrCoeffPair.first], &attrCoeffPair.second);
element_pow_zn(Zy, &Cw[attrCoeffPair.first], &attrCoeffPair.second);
if (pastFirst)
{
element_mul(&Cs, &Cs, Zy);
}
else
{
pastFirst = true;
element_set(&Cs, Zy);
}
}
for (auto &attrCoeffPair : attrs)
{
element_clear(&attrCoeffPair.second);
}
element_clear(Zy);
}
std::vector<uint8_t> encrypt(PublicParams ¶ms,
const vector<int> &attributes,
const string &message,
Cw_t &Cw)
{
element_s Cs;
Cw = createSecret(params, attributes, Cs);
// Use the key to encrypt the data using a symmetric cipher.
size_t messageLen = message.size() + 1; // account for terminating byte
size_t cipherMaxLen = messageLen + AES_BLOCK_SIZE;
vector<uint8_t> ciphertext(cipherMaxLen);
array<uint8_t, AES_KEY_SIZE> key;
hashElement(&Cs, key.data());
size_t clength = 0;
symEncrypt((uint8_t *)message.c_str(), messageLen, key.data(), ciphertext.data(), &clength);
ciphertext.resize(clength);
element_clear(&Cs);
return ciphertext;
}
string decrypt(DecryptionKey &key,
Cw_t &Cw,
const vector<int> &attributes,
const vector<uint8_t> &ciphertext)
{
element_s Cs;
recoverSecret(key, Cw, attributes, Cs);
vector<uint8_t> plaintext(ciphertext.size());
size_t plaintextLen = 0;
array<uint8_t, AES_KEY_SIZE> symKey;
hashElement(&Cs, symKey.data());
symDecrypt(ciphertext.data(), ciphertext.size(), symKey.data(), plaintext.data(), &plaintextLen);
plaintext.resize(plaintextLen);
string message((char *)plaintext.data());
element_clear(&Cs);
return message;
}