-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencryption_tests.rs
82 lines (63 loc) · 2.6 KB
/
encryption_tests.rs
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
use num::traits::ToPrimitive;
use paillier::*;
use proptest::prelude::*;
#[cfg(test)]
mod tests {
use super::*;
use cached::cached;
cached! {
GENERATE_PRIMES;
fn gen_same_primes() -> (PublicKey, PrivateKey) = {
generate_keypair().expect("Couldn't generate keypair")
}
}
#[test]
fn can_encrypt_and_decrypt() {
let (public_key, private_key) = gen_same_primes();
let plaintext = 123.into();
let ciphertext = encrypt(&plaintext, &public_key).expect("Couldn't encrypt plaintext");
let decrypted = decrypt(&ciphertext, &private_key).expect("Couldn't decrypt ciphertext");
assert_eq!(plaintext, decrypted);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 25, ..ProptestConfig::default() })]
#[test]
fn can_add_ciphertexts(x: u64, y: u64) {
// Ensure that x + y doesn't overflow
prop_assume!(x.checked_add(y).is_some());
let p1 = PlainText::from(x);
let p2 = PlainText::from(y);
let (public_key, private_key) = gen_same_primes();
let c1 = encrypt(&p1, &public_key).expect("c1 encryption failed");
let c2 = encrypt(&p2, &public_key).expect("c2 encryption failed");
let c = c1 + c2;
let PlainText(decrypted) = decrypt(&c, &private_key).expect("Couldn't decrypt result!");
prop_assert_eq!(x + y, decrypted.to_u64().expect("Couldn't convert decrypted result to u64"));
}
#[test]
fn can_multiply_ciphertext_and_plaintext(x in 0u64..1_000_000, y in 0u64..1_000) {
let p1 = PlainText::from(x);
let p2 = PlainText::from(y);
let (public_key, private_key) = gen_same_primes();
let c1 = encrypt(&p1, &public_key).expect("c1 encryption failed");
let c = c1.clone() * p2.clone();
let c_commutative = p2 * c1;
let PlainText(decrypted) = decrypt(&c, &private_key).expect("Couldn't decrypt result!");
prop_assert_eq!(x * y, decrypted.to_u64().expect("Couldn't convert decrypted result to u64"));
prop_assert_eq!(c, c_commutative);
}
#[test]
fn can_subtract_cipertexts(x: u64, y: u64) {
// Ensure that x - y >= 0
prop_assume!(x >= y);
let p1 = PlainText::from(x);
let p2 = PlainText::from(y);
let (public_key, private_key) = gen_same_primes();
let c1 = encrypt(&p1, &public_key).expect("c1 encryption failed");
let c2 = encrypt(&p2, &public_key).expect("c2 encryption failed");
let c = c1 - c2;
let PlainText(decrypted) = decrypt(&c, &private_key).expect("Couldn't decrypt result!");
prop_assert_eq!(x - y, decrypted.to_u64().expect("Couldn't convert decrypted result to i64"));
}
}
}