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
//! Types and traits which lift `u32` type to FHE compatible
//! `Enc` struct
use super::algebra::{invert_3x3, Mod231, Q231};
use nalgebra::Matrix3;
use num_traits::Zero;
use rand::prelude::*;
use std::fmt;
use std::ops::{Add, AddAssign, Mul, MulAssign};

/// Wrapper type for lifting `u32` type to FHE compatible
/// form
///
/// All FHE operations (currently, addition and multiplication)
/// are defined in terms of this type.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Enc {
    inner: Matrix3<Q231>,
}

impl Enc {
    #[inline]
    fn enc(key_pair: &KeyPair, value: u32) -> Self {
        let enc: Matrix3<_> = Q231::from(Mod231::from(value)).into();
        let inner = key_pair.forwards * enc * key_pair.backwards;

        Self { inner }
    }

    #[inline]
    fn dec(&self, key_pair: &KeyPair) -> u32 {
        let dec = key_pair.backwards * self.inner * key_pair.forwards;
        dec[0].w.0
    }
}

impl fmt::Display for Enc {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        self.inner.fmt(f)
    }
}

impl Add for Enc {
    type Output = Self;

    #[inline]
    fn add(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner + rhs.inner,
        }
    }
}

impl AddAssign for Enc {
    #[inline]
    fn add_assign(&mut self, rhs: Self) {
        *self = *self + rhs
    }
}

impl Mul for Enc {
    type Output = Self;

    #[inline]
    fn mul(self, rhs: Self) -> Self::Output {
        Self {
            inner: self.inner * rhs.inner,
        }
    }
}

impl MulAssign for Enc {
    #[inline]
    fn mul_assign(&mut self, rhs: Self) {
        *self = *self * rhs
    }
}

/// Type representing a key pair which can be used for encrypting
/// and decrypting data
#[derive(Debug)]
pub struct KeyPair {
    forwards: Matrix3<Q231>,
    backwards: Matrix3<Q231>,
}

impl KeyPair {
    /// Generates new random key pair
    #[inline]
    pub fn new() -> Self {
        let mut rng = thread_rng();
        let mut forwards = Matrix3::<Q231>::zero().map(|_| rng.gen::<Q231>());
        let mut maybe_backwards = invert_3x3(&forwards);

        while maybe_backwards.is_none() {
            forwards = Matrix3::<Q231>::zero().map(|_| rng.gen::<Q231>());
            maybe_backwards = invert_3x3(&forwards);
        }

        Self {
            forwards,
            backwards: maybe_backwards.unwrap(),
        }
    }
}

impl Default for KeyPair {
    /// Creates randomized key pair
    #[inline]
    fn default() -> Self {
        Self::new()
    }
}

/// Helper trait for encrypting data
pub trait Encrypt {
    type Output;

    /// Encrypts data using `key_pair` and outputs `Self::Output`
    fn encrypt(key_pair: &KeyPair, value: u32) -> Self::Output;
}

/// Helper trait for decrypting data
pub trait Decrypt {
    type Output;

    /// Decrypts `Self` using `key_pair` and outputs data
    fn decrypt(&self, key_pair: &KeyPair) -> Self::Output;
}

impl Encrypt for Enc {
    type Output = Enc;

    #[inline]
    fn encrypt(key_pair: &KeyPair, value: u32) -> Self::Output {
        Enc::enc(key_pair, value)
    }
}

impl<'a> Encrypt for &'a Enc {
    type Output = Enc;

    #[inline]
    fn encrypt(key_pair: &KeyPair, value: u32) -> Self::Output {
        Enc::enc(key_pair, value)
    }
}

impl Decrypt for Enc {
    type Output = u32;

    #[inline]
    fn decrypt(&self, key_pair: &KeyPair) -> Self::Output {
        self.dec(key_pair)
    }
}

impl<'a> Decrypt for &'a Enc {
    type Output = u32;

    #[inline]
    fn decrypt(&self, key_pair: &KeyPair) -> Self::Output {
        self.dec(key_pair)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn identity() {
        let key_pair = KeyPair::default();
        assert_eq!(
            key_pair.forwards * key_pair.backwards,
            key_pair.backwards * key_pair.forwards
        )
    }

    #[test]
    fn idempotence() {
        let key_pair = KeyPair::default();
        assert_eq!(1, Enc::encrypt(&key_pair, 1).decrypt(&key_pair));
    }

    /*
    #[quickcheck]
    fn paranoid_enc_mul_homomorphic(x: u32, y: u32) -> TestResult {
        if x < MODULUS && y < MODULUS {
            let key_pair = KeyPair::new();
            let x1 = Enc::encrypt(&key_pair, x);
            let y1 = Enc::encrypt(&key_pair, y);
            let r = x1 * y1;
            return TestResult::from_bool( r.decrypt(&key_pair) == normalize_u64(x as u64  * y as u64));
        }

        TestResult::discard()
    }
   */

    #[quickcheck]
    fn prop_enc_mul_homomorphic(x: u32, y: u32) -> bool {
        let key_pair = KeyPair::new();
        let enc_x = Enc::encrypt(&key_pair, x);
        let enc_y = Enc::encrypt(&key_pair, y);
        (enc_x * enc_y).decrypt(&key_pair) == x * y
    }

    #[quickcheck]
    fn prop_enc_add_homomorphic(x: u32, y: u32) -> bool {
        let key_pair = KeyPair::new();
        let enc_x = Enc::encrypt(&key_pair, x);
        let enc_y = Enc::encrypt(&key_pair, y);
        (enc_x + enc_y).decrypt(&key_pair) == x + y
    }

}