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
#![doc = include_str!("../README.md")]
#![forbid(missing_docs)]

mod decryption_key;
mod encryption_key;
pub mod utils;

#[cfg(feature = "serde")]
mod serde;

use std::fmt;

use rand_core::{CryptoRng, RngCore};
use rug::Integer;

/// Paillier ciphertext
pub type Ciphertext = Integer;
/// Paillier plaintext
pub type Plaintext = Integer;
/// Paillier nonce
pub type Nonce = Integer;

pub use self::{decryption_key::DecryptionKey, encryption_key::EncryptionKey};

/// Error type used in the library
#[derive(Debug, thiserror::Error)]
#[error(transparent)]
pub struct Error(#[from] Reason);

#[derive(Debug, thiserror::Error)]
enum Reason {
    #[error("p,q are invalid")]
    InvalidPQ,
    #[error("encryption error")]
    Encrypt,
    #[error("decryption error")]
    Decrypt,
    #[error("homomorphic operation failed: invalid inputs")]
    Ops,
    #[error("could not precompute data for faster exponentiation")]
    BuildFastExp,
    #[error("bug occurred")]
    Bug(#[source] Bug),
}

#[derive(Debug, thiserror::Error)]
enum Bug {
    #[error("pow mod undefined")]
    PowModUndef,
}

impl From<Bug> for Error {
    fn from(err: Bug) -> Self {
        Error(Reason::Bug(err))
    }
}

mod sealed {
    pub trait Sealed {}
    impl Sealed for crate::EncryptionKey {}
    impl Sealed for crate::DecryptionKey {}
}

/// Any key capable of encryption
///
/// Both encryption and decryption keys can be used to carry out encryption. Moreover, encryption
/// using decryption key is faster.
///
/// ## Example
/// This trait can be used, for instance, to accept an encryption key as an argument to the function
/// and benefit from faster encryption if decryption key is provided.
///
/// ```rust
/// use fast_paillier::{AnyEncryptionKey, Error};
/// use rug::Integer;
///
/// // This function accepts both encryption and decryption key. If decryption key is provided,
/// // it'll be more efficient
/// fn some_function(ek: &dyn AnyEncryptionKey) -> Result<Integer, Error> {
///     // ...
/// # let x = Integer::from(123); let r = Integer::from(321);
///     let ciphertext = ek.encrypt_with(&x, &r)?;
///     Ok(ciphertext)
/// }
/// ```
pub trait AnyEncryptionKey: sealed::Sealed {
    /// Returns `N`
    fn n(&self) -> &Integer;
    /// Returns `N^2`
    fn nn(&self) -> &Integer;
    /// Returns `N/2`
    fn half_n(&self) -> &Integer;

    /// Encrypts the plaintext `x` in `{-N/2, .., N_2}` with `nonce` in `Z*_n`
    ///
    /// Returns error if inputs are not in specified range
    fn encrypt_with(&self, x: &Plaintext, nonce: &Nonce) -> Result<Ciphertext, Error>;

    /// Homomorphic addition of two ciphertexts
    ///
    /// ```text
    /// oadd(Enc(a1), Enc(a2)) = Enc(a1 + a2)
    /// ```
    fn oadd(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error>;
    /// Homomorphic subtraction of two ciphertexts
    ///
    /// ```text
    /// osub(Enc(a1), Enc(a2)) = Enc(a1 - a2)
    /// ```
    fn osub(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error>;
    /// Homomorphic multiplication of scalar at ciphertext
    ///
    /// ```text
    /// omul(a, Enc(c)) = Enc(a * c)
    /// ```
    fn omul(&self, scalar: &Integer, ciphertext: &Ciphertext) -> Result<Ciphertext, Error>;
    /// Homomorphic negation of a ciphertext
    ///
    /// ```text
    /// oneg(Enc(a)) = Enc(-a)
    /// ```
    fn oneg(&self, ciphertext: &Ciphertext) -> Result<Ciphertext, Error>;

    /// Checks whether `x` is `{-N/2, .., N/2}`
    fn in_signed_group(&self, x: &Integer) -> bool;
}

/// Additional functionality implemented for [AnyEncryptionKey]
pub trait AnyEncryptionKeyExt: AnyEncryptionKey {
    /// Encrypts the plaintext `x` in `{-N/2, .., N_2}`
    ///
    /// Nonce is sampled randomly using `rng`.
    ///
    /// Returns error if plaintext is not in specified range
    fn encrypt_with_random(
        &self,
        rng: &mut (impl RngCore + CryptoRng),
        x: &Plaintext,
    ) -> Result<(Ciphertext, Nonce), Error>;
}

impl<E: AnyEncryptionKey> AnyEncryptionKeyExt for E {
    fn encrypt_with_random(
        &self,
        rng: &mut (impl RngCore + CryptoRng),
        x: &Plaintext,
    ) -> Result<(Ciphertext, Nonce), Error> {
        let nonce = utils::sample_in_mult_group(rng, self.n());
        let ciphertext = self.encrypt_with(x, &nonce)?;
        Ok((ciphertext, nonce))
    }
}

impl AnyEncryptionKey for EncryptionKey {
    fn n(&self) -> &Integer {
        self.n()
    }

    fn nn(&self) -> &Integer {
        self.nn()
    }

    fn half_n(&self) -> &Integer {
        self.half_n()
    }

    fn encrypt_with(&self, x: &Plaintext, nonce: &Nonce) -> Result<Ciphertext, Error> {
        self.encrypt_with(x, nonce)
    }

    fn oadd(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error> {
        self.oadd(c1, c2)
    }

    fn osub(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error> {
        self.osub(c1, c2)
    }

    fn omul(&self, scalar: &Integer, ciphertext: &Ciphertext) -> Result<Ciphertext, Error> {
        self.omul(scalar, ciphertext)
    }

    fn oneg(&self, ciphertext: &Ciphertext) -> Result<Ciphertext, Error> {
        self.oneg(ciphertext)
    }

    fn in_signed_group(&self, x: &Integer) -> bool {
        self.in_signed_group(x)
    }
}

impl AnyEncryptionKey for DecryptionKey {
    fn n(&self) -> &Integer {
        self.encryption_key().n()
    }

    fn nn(&self) -> &Integer {
        self.encryption_key().nn()
    }

    fn half_n(&self) -> &Integer {
        self.encryption_key().half_n()
    }

    fn encrypt_with(&self, x: &Plaintext, nonce: &Nonce) -> Result<Ciphertext, Error> {
        self.encrypt_with(x, nonce)
    }

    fn oadd(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error> {
        self.encryption_key().oadd(c1, c2)
    }

    fn osub(&self, c1: &Ciphertext, c2: &Ciphertext) -> Result<Ciphertext, Error> {
        self.encryption_key().osub(c1, c2)
    }

    fn omul(&self, scalar: &Integer, ciphertext: &Ciphertext) -> Result<Ciphertext, Error> {
        self.omul(scalar, ciphertext)
    }

    fn oneg(&self, ciphertext: &Ciphertext) -> Result<Ciphertext, Error> {
        self.encryption_key().oneg(ciphertext)
    }

    fn in_signed_group(&self, x: &Integer) -> bool {
        self.encryption_key().in_signed_group(x)
    }
}

impl<'a> fmt::Debug for dyn AnyEncryptionKey + 'a {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PaillierEncKey")
            .field("N", self.n())
            .finish_non_exhaustive()
    }
}