rabe 0.4.2

ABE Schemes implemented in rust.
Documentation
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
//! `BSW` scheme by John Bethencourt, Amit Sahai, Brent Waters.
//!
//! * Developped by John Bethencourt, Amit Sahai, Brent Waters, "Ciphertext-Policy Attribute-Based Encryption"
//! * Published in Security and Privacy, 2007. SP'07. IEEE Symposium on. IEEE
//! * Available from <https://doi.org/10.1109/SP.2007.11>
//! * Type: encryption (attribute-based)
//! * Setting: bilinear groups (asymmetric)
//! * Authors: Georg Bramm
//! * Date: 04/2018
//!
//! # Examples
//!
//! ```
//!use rabe::schemes::bsw::*;
//! use rabe::utils::policy::pest::PolicyLanguage;
//! let (pk, msk) = setup();
//! let plaintext = String::from("dance like no one's watching, encrypt like everyone is!").into_bytes();
//! let policy = String::from(r#""A" and "B""#);
//! let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::HumanPolicy, &plaintext).unwrap();
//! let sk: CpAbeSecretKey = keygen(&pk, &msk, &vec!["A", "B"]).unwrap();
//! assert_eq!(decrypt(&sk, &ct_cp).unwrap(), plaintext);
//! ```
use rabe_bn::{Fr, G1, G2, Gt, pairing};
use rand::Rng;
use utils::{
    secretsharing::{gen_shares_policy, calc_pruned, calc_coefficients},
    tools::*,
    aes::*,
    hash::*
};
use utils::policy::pest::{PolicyLanguage, parse, PolicyType};
use crate::error::RabeError;
use utils::secretsharing::remove_index;
#[cfg(feature = "borsh")]
use borsh::{BorshSerialize, BorshDeserialize};
#[cfg(feature = "serde")]
use serde::{Serialize, Deserialize};

/// A BSW Public Key (PK)
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CpAbePublicKey {
    pub g1: G1,
    pub g2: G2,
    pub h: G1,
    pub f: G2,
    pub e_gg_alpha: Gt,
}

/// A BSW Master Key (MSK)
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CpAbeMasterKey {
    pub beta: Fr,
    pub g2_alpha: G2,
}

/// A BSW Ciphertext (CT)
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CpAbeCiphertext {
    pub policy: (String, PolicyLanguage),
    pub c: G1,
    pub c_p: Gt,
    pub c_y: Vec<CpAbeAttribute>,
    pub data: Vec<u8>,
}

/// A BSW Secret User Key (SK)
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CpAbeSecretKey {
    pub d: G2,
    pub d_j: Vec<CpAbeAttribute>,
}

/// A BSW Attribute
#[derive(Clone, PartialEq, Debug)]
#[cfg_attr(feature = "borsh", derive(BorshSerialize, BorshDeserialize))]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct CpAbeAttribute {
    pub string: String,
    pub g1: G1,
    pub g2: G2,
}

/// The setup algorithm of BSW CP-ABE. Generates a new CpAbePublicKey and a new CpAbeMasterKey.
pub fn setup() -> (CpAbePublicKey, CpAbeMasterKey) {
    // random number generator
    let mut rng = rand::thread_rng();
    // generator of group G1: g1 and generator of group G2: g2
    let g1:G1 = rng.gen();
    let g2:G2 = rng.gen();
    // random
    let beta:Fr = rng.gen();
    let alpha:Fr = rng.gen();
    // vectors
    // calulate h and f
    let h = g1 * beta;
    let f = g2 * beta.inverse().unwrap();
    // calculate g2^alpha
    let g2_alpha = g2 * alpha;
    // calculate the pairing between g1 and g2^alpha
    let e_gg_alpha = pairing(g1, g2_alpha);

    // return PK and MSK
    return (
        CpAbePublicKey { g1, g2, h, f, e_gg_alpha },
        CpAbeMasterKey { beta, g2_alpha },
    );
}

/// The key generation algorithm of BSW CP-ABE. Generates a CpAbeSecretKey using a CpAbePublicKey, a CpAbeMasterKey and a set of attributes given as Vec<String>.
///
/// # Arguments
///
///	* `pk` - A Public Key (PK), generated by the function setup()
///	* `msk` - A Master Key (MSK), generated by the function setup()
///	* `attributes` - A Vector of String attributes assigned to this user key
///
pub fn keygen(
    pk: &CpAbePublicKey,
    msk: &CpAbeMasterKey,
    attributes: &[&str],
) -> Option<CpAbeSecretKey> {
    // if no attibutes or an empty policy
    // maybe add empty msk also here
    if attributes.is_empty() || attributes.len() == 0 {
        return None;
    }
    // random number generator
    let mut rng = rand::thread_rng();
    // generate random r1 and r2 and sum of both
    // compute Br as well because it will be used later too
    let r:Fr = rng.gen();
    let g2_r = pk.g2 * r;
    let d = (msk.g2_alpha + g2_r) * msk.beta.inverse().unwrap();
    let mut d_j: Vec<CpAbeAttribute> = Vec::new();
    for j in attributes {
        let r_j:Fr = rng.gen();
        d_j.push(CpAbeAttribute {
            string: j.to_string(), // attribute name
            g1: pk.g1 * r_j, // D_j Prime
            g2: g2_r + (sha3_hash(pk.g2, j).expect("could not hash _j") * r_j), // D_j
        });
    }
    return Some(CpAbeSecretKey { d, d_j });
}

/// The delegate generation algorithm of BSW CP-ABE. Generates a new CpAbeSecretKey using a CpAbePublicKey, a CpAbeSecretKey and a subset of attributes (of the key _sk) given as Vec<String>.
///
/// # Arguments
///
///	* `pk` - A Public Key (PK), generated by the function setup()
///	* `sk` - A Secret User Key (SK), generated by the function keygen()
///	* `subset` - A Vector of String attributes delegated to the new user key
///
pub fn delegate(
    pk: &CpAbePublicKey,
    sk: &CpAbeSecretKey,
    subset: &[&str],
) -> Option<CpAbeSecretKey> {
    let attr_str = sk.d_j
        .iter()
        .map(|val| val.string.as_str())
        .collect::<Vec<_>>();
    return if !is_subset(subset, &attr_str) {
        println!("Error: the given attribute set is not a subset of the given sk.");
        None
    } else {
        // if no attibutes or an empty policy
        // maybe add empty msk also here
        if subset.is_empty() || subset.len() == 0 {
            println!("Error: the given attribute subset is empty.");
            return None;
        }
        // random number generator
        let mut rng = rand::thread_rng();
        // generate random r
        let r: Fr = rng.gen();
        // calculate derived _k_0
        let mut d_j: Vec<CpAbeAttribute> = Vec::new();
        // calculate derived attributes
        for attr in subset {
            let r_j: Fr = rng.gen();
            let d_j_val = sk.d_j
                .iter()
                .find(|x| x.string == attr.to_string())
                .map(|x| (x.g1, x.g2))
                .unwrap();
            d_j.push(CpAbeAttribute {
                string: attr.to_string(),
                g1: d_j_val.0 + (pk.g1 * r_j),
                g2: d_j_val.1 + (sha3_hash(pk.g2, attr.as_ref()).expect("could not hash _attr") * r_j) + (pk.g2 * r),
            });
        }
        Some(CpAbeSecretKey {
            d: sk.d + (pk.f * r),
            d_j,
        })
    }
}

/// The encrypt algorithm of BSW CP-ABE. Generates a new CpAbeCiphertext using an Ac17PublicKey, an access policy given as String and some plaintext data given as [u8].
///
/// # Arguments
///
///	* `pk` - A Public Key (PK), generated by the function setup()
///	* `policy` - An access policy given as JSON String
///	* `language` - The policy language
///	* `plaintext` - plaintext data given as a Vector of u8
///
pub fn encrypt(
    pk: &CpAbePublicKey,
    policy: &str,
    language: PolicyLanguage,
    plaintext: &[u8],
) -> Result<CpAbeCiphertext, RabeError> {
    if plaintext.is_empty() || policy.is_empty() {
        RabeError::new("Error in bsw/encrypt: data or policy is empty.");
    }
    let mut rng = rand::thread_rng();
    // the shared root secret
    let secret:Fr = rng.gen();
    let msg: Gt = rng.gen();
    match parse(policy, language) {
        Ok(policy_value) => {
            let shares: Vec<(String, Fr)> = gen_shares_policy(secret, &policy_value, None).unwrap();
            let c = pk.h * secret;
            let c_p = pk.e_gg_alpha.pow(secret) * msg;
            let mut c_y: Vec<CpAbeAttribute> = Vec::new();
            for (node, i_val) in shares.clone() {
                let j = remove_index(&node);
                c_y.push(CpAbeAttribute {
                    string: node,
                    g1: pk.g1 * i_val,
                    g2: sha3_hash(pk.g2, &j).expect("could not hash j") * i_val,
                });
            }
            match encrypt_symmetric(msg, &plaintext.to_vec()) {
                Ok(data) => Ok(CpAbeCiphertext { policy: (policy.to_string(), language), c, c_p, c_y, data }),
                Err(e) => Err(e)
            }
        }
        Err(e) => Err(e)
    }
}

/// The decrypt algorithm of BSW CP-ABE. Reconstructs the original plaintext data as Vec<u8>, given a CpAbeCiphertext with a matching CpAbeSecretKey.
///
/// # Arguments
///
///	* `sk` - A Secret Key (SK), generated by the function keygen()
///	* `ct` - An BSW CP-ABE Ciphertext
///
pub fn decrypt(
    sk: &CpAbeSecretKey,
    ct: &CpAbeCiphertext
) -> Result<Vec<u8>, RabeError> {
    let attr = sk.d_j
        .iter()
        .map(|v| v.string.clone() )
        .collect::<Vec<_>>();
    match parse(ct.policy.0.as_ref(), ct.policy.1) {
        Ok(policy_value) => {
            return if traverse_policy(&attr, &policy_value, PolicyType::Leaf) == false {
                Err(RabeError::new("Error in bsw/encrypt: attributes do not match policy."))
            } else {
                match calc_pruned(&attr, &policy_value, None) {
                    Err(e) => Err(e),
                    Ok(pruned) => {
                        if !pruned.0 {
                            Err(RabeError::new("Error in bsw/encrypt: attributes do not match policy."))
                        } else {
                            let mut z: Vec<(String, Fr)> = Vec::new();
                            z = calc_coefficients(&policy_value, Some(Fr::one()), z, None).unwrap();
                            let mut a = Gt::one();
                            for _i in pruned.1 {
                                let _k = _i.0;
                                let _j = _i.1;
                                match ct.c_y.iter().find(|x| x.string == _j.to_string()) {
                                    Some(c_y) => {
                                        match sk.d_j.iter().find(|x| x.string == _k.to_string()) {
                                            Some(d_j) => {
                                                for _z_tuple in z.iter() {
                                                    if _z_tuple.0 == _j {
                                                        a = a *
                                                            (pairing(c_y.g1, d_j.g2) *
                                                                pairing(d_j.g1, c_y.g2).inverse())
                                                                .pow(_z_tuple.1);
                                                    }
                                                }
                                            }
                                            None => {
                                                // do nothing
                                            }
                                        }
                                    }
                                    None => {
                                        // do nothing
                                    }
                                }
                            }
                            let _msg = ct.c_p * ((pairing(ct.c, sk.d)) * a.inverse()).inverse();
                            // Decrypt plaintext using derived secret from cp-abe scheme
                            decrypt_symmetric(_msg, &ct.data)
                        }
                    }
                }
            }
        }
        Err(e) => Err(e)
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn or() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<&str> = Vec::new();
        att_matching.push("D");
        att_matching.push("B");

        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("C");
        att_not_matching.push("D");

        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();

        // our policy
        let policy = String::from(r#"{"name": "or", "children": [{"name": "A"}, {"name": "B"}]}"#);

        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();

        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);

        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn and10() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<String> = Vec::new();
        for n in 1..11 {
            att_matching.push(["attr".to_string(), n.to_string()].concat());
        }
        let att: Vec<&str>  = att_matching.iter().map(|x| x.as_ref()).collect();
        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("attr201");
        att_not_matching.push("attr200");

        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();

        let mut _policy = String::from("{\"name\": \"and\", \"children\": [");
        for n in 1..11 {
            let mut _current = String::from("{\"name\": \"attr");
            if n < 10 {
                _current.push_str(&n.to_string());
                _current.push_str(&String::from("\"}, "));
            } else {
                _current.push_str(&n.to_string());
                _current.push_str(&String::from("\"}]"));
            }
            _policy.push_str(&_current);
        }
        _policy.push_str(&String::from("}"));
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &_policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();

        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);

        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn nested() {
        // setup scheme
        let (pk, msk) = setup();
        let _num_nested = 30; // maximum at about 50 to 60
        // a set of two attributes matching the policy
        let mut att_matching: Vec<String> = Vec::new();
        for _i in 1..(_num_nested + 1) {
            att_matching.push(["a".to_string(), _i.to_string()].concat());
        }
        let attr: Vec<&str> = att_matching.iter().map(|x| x.as_ref()).collect();
        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("x");
        att_not_matching.push("y");
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        let mut policy = String::from("{\"name\":\"and\", \"children\": [{\"name\": \"a2\"}, {\"name\": \"a1\"}]}");
        for _i in 3.._num_nested {
            let mut policy_str = String::from("{\"name\":\"and\", \"children\":[");
            policy_str.push_str("{\"name\":\"");
            policy_str.push_str(&attr[_i - 1]);
            policy_str.push_str("\"},");
            policy_str.push_str(&policy);
            policy_str.push_str("]}");
            policy = policy_str.clone();
        }
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &attr).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn or3() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<&str> = Vec::new();
        att_matching.push("A");

        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("B");
        att_not_matching.push("C");

        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();

        // our policy
        let policy = String::from(r#"{"name": "or", "children": [{"name": "X"}, {"name": "Y"}, {"name": "A"}]}"#);

        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();

        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn and() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<&str> = Vec::new();
        att_matching.push("A");
        att_matching.push("B");
        att_matching.push("C");
        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("A");
        att_not_matching.push("D");
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        // our policy
        let policy = String::from(r#"{"name": "and", "children":  [{"name": "A"}, {"name": "B"}]}"#);
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn dual_attributes() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<&str> = Vec::new();
        att_matching.push("A");
        att_matching.push("B");
        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("A");
        att_not_matching.push("C");
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        // our policy
        let policy = String::from(r#"{"name": "or", "children": [{"name": "and", "children":  [{"name": "A"}, {"name": "B"}]}, {"name": "and", "children":  [{"name": "B"}, {"name": "C"}]}]}"#);
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn and3() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let mut att_matching: Vec<&str> = Vec::new();
        att_matching.push("A");
        att_matching.push("B");
        att_matching.push("C");
        // a set of two attributes NOT matching the policy
        let mut att_not_matching: Vec<&str> = Vec::new();
        att_not_matching.push("A");
        att_not_matching.push("D");
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        // our policy
        let policy = String::from(r#"{"name": "and", "children":  [{"name": "A"}, {"name": "B"}, {"name": "C"}]}"#);
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);

        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn or_and() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of two attributes matching the policy
        let att_matching: Vec<&str> = vec!["A","B","C","D"];
        // a set of two attributes NOT matching the policy
        let att_not_matching: Vec<&str> = vec!["A","C"];
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        // our policy
        let policy = String::from(r#"{"name": "or", "children": [{"name": "and", "children":  [{"name": "A"}, {"name": "B"}]}, {"name": "and", "children":  [{"name": "C"}, {"name": "D"}]}]}"#);
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&keygen(&pk, &msk, &att_matching).unwrap(), &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
        let _no_match = decrypt(&keygen(&pk, &msk, &att_not_matching).unwrap(), &ct_cp);
        assert_eq!(_no_match.is_ok(), false);
    }

    #[test]
    fn delegate_ab() {
        // setup scheme
        let (pk, msk) = setup();
        // a set of three attributes matching the policy
        let att_matching: Vec<&str> = vec!["A","B","C"];
        // a set of two delegated attributes
        let delegate_att: Vec<&str> = vec!["A","B"];
        // our plaintext
        let plaintext = String::from("dance like no one's watching, encrypt like everyone is!")
            .into_bytes();
        // our policy
        let policy = String::from(r#"{"name": "and", "children":  [{"name": "A"}, {"name": "B"}]}"#);
        // cp-abe ciphertext
        let ct_cp: CpAbeCiphertext = encrypt(&pk, &policy, PolicyLanguage::JsonPolicy, &plaintext).unwrap();
        // a cp-abe SK key matching
        let sk: CpAbeSecretKey = keygen(&pk, &msk, &att_matching).unwrap();
        // delegate a cp-abe SK
        let del: CpAbeSecretKey = delegate(&pk, &sk, &delegate_att).unwrap();
        // and now decrypt again with mathcing sk
        let _match = decrypt(&del, &ct_cp);
        assert_eq!(_match.is_ok(), true);
        assert_eq!(_match.unwrap(), plaintext);
    }
}