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
//! Cryptographic keys for ElGamal encryption.

use base64ct::{Base64UrlUnpadded, Encoding};
use rand_core::{CryptoRng, RngCore};
use zeroize::Zeroize;

use core::{fmt, ops};

use crate::{
    alloc::{vec, Vec},
    group::Group,
};

mod impls;

/// Secret key for ElGamal encryption and related protocols. This is a thin wrapper around
/// the [`Group`] scalar.
pub struct SecretKey<G: Group>(G::Scalar);

impl<G: Group> fmt::Debug for SecretKey<G> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("SecretKey")
            .field("public", &PublicKey::from(self))
            .finish()
    }
}

impl<G: Group> Clone for SecretKey<G> {
    fn clone(&self) -> Self {
        SecretKey(self.0)
    }
}

impl<G: Group> Drop for SecretKey<G> {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

impl<G: Group> SecretKey<G> {
    pub(crate) fn new(scalar: G::Scalar) -> Self {
        SecretKey(scalar)
    }

    /// Generates a random secret key.
    pub fn generate<R: CryptoRng + RngCore>(rng: &mut R) -> Self {
        SecretKey(G::generate_scalar(rng))
    }

    /// Deserializes a secret key from bytes. If bytes do not represent a valid scalar,
    /// returns `None`.
    pub fn from_bytes(bytes: &[u8]) -> Option<Self> {
        if bytes.len() != G::SCALAR_SIZE {
            return None;
        }
        G::deserialize_scalar(bytes).map(SecretKey)
    }

    /// Exposes the scalar equivalent to this key.
    pub fn expose_scalar(&self) -> &G::Scalar {
        &self.0
    }
}

impl<G: Group> ops::Add for SecretKey<G> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        Self(self.0 + rhs.0)
    }
}

impl<G: Group> ops::AddAssign for SecretKey<G> {
    fn add_assign(&mut self, rhs: Self) {
        self.0 = self.0 + rhs.0;
    }
}

impl<G: Group> ops::Sub for SecretKey<G> {
    type Output = Self;

    fn sub(self, rhs: Self) -> Self {
        Self(self.0 - rhs.0)
    }
}

impl<G: Group> ops::SubAssign for SecretKey<G> {
    fn sub_assign(&mut self, rhs: Self) {
        self.0 = self.0 - rhs.0;
    }
}

impl<G: Group> ops::Mul<&G::Scalar> for SecretKey<G> {
    type Output = Self;

    fn mul(self, &k: &G::Scalar) -> Self {
        Self(self.0 * k)
    }
}

impl<G: Group> ops::Mul<&G::Scalar> for &SecretKey<G> {
    type Output = SecretKey<G>;

    fn mul(self, &k: &G::Scalar) -> SecretKey<G> {
        SecretKey(self.0 * k)
    }
}

/// Public key for ElGamal encryption and related protocols.
///
/// # Implementation details
///
/// We store both the original bytes (which are used in zero-knowledge proofs)
/// and its decompression into a [`Group`] element.
/// This increases the memory footprint, but speeds up generating / verifying proofs.
pub struct PublicKey<G: Group> {
    bytes: Vec<u8>,
    element: G::Element,
}

impl<G: Group> Clone for PublicKey<G> {
    fn clone(&self) -> Self {
        PublicKey {
            bytes: self.bytes.clone(),
            element: self.element,
        }
    }
}

impl<G: Group> fmt::Debug for PublicKey<G> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_tuple("PublicKey")
            .field(&Base64UrlUnpadded::encode_string(&self.bytes))
            .finish()
    }
}

impl<G> PartialEq for PublicKey<G>
where
    G: Group,
{
    fn eq(&self, other: &Self) -> bool {
        self.bytes == other.bytes
    }
}

impl<G: Group> PublicKey<G> {
    /// Deserializes a public key from bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if `bytes` has invalid byte size, does not represent a valid group element
    /// or represents the group identity.
    pub fn from_bytes(bytes: &[u8]) -> Result<Self, PublicKeyConversionError> {
        if bytes.len() != G::ELEMENT_SIZE {
            return Err(PublicKeyConversionError::InvalidByteSize);
        }

        let element =
            G::deserialize_element(bytes).ok_or(PublicKeyConversionError::InvalidGroupElement)?;
        if G::is_identity(&element) {
            Err(PublicKeyConversionError::IdentityKey)
        } else {
            Ok(Self {
                bytes: bytes.to_vec(),
                element,
            })
        }
    }

    pub(crate) fn from_element(element: G::Element) -> Self {
        let mut element_bytes = vec![0_u8; G::ELEMENT_SIZE];
        G::serialize_element(&element, &mut element_bytes);
        PublicKey {
            element,
            bytes: element_bytes,
        }
    }

    /// Returns bytes representing the group element corresponding to this key.
    pub fn as_bytes(&self) -> &[u8] {
        &self.bytes
    }

    /// Returns the group element equivalent to this key.
    pub fn as_element(&self) -> G::Element {
        self.element
    }
}

impl<G: Group> From<&SecretKey<G>> for PublicKey<G> {
    fn from(secret_key: &SecretKey<G>) -> Self {
        let element = G::mul_generator(&secret_key.0);
        Self::from_element(element)
    }
}

/// Errors that can occur when converting other types to [`PublicKey`].
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum PublicKeyConversionError {
    /// Invalid size of the byte buffer.
    InvalidByteSize,
    /// Byte buffer has correct size, but does not represent a group element.
    InvalidGroupElement,
    /// Underlying group element is the group identity.
    IdentityKey,
}

impl fmt::Display for PublicKeyConversionError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::InvalidByteSize => "invalid size of the byte buffer",
            Self::InvalidGroupElement => {
                "byte buffer has correct size, but does not represent a group element"
            }
            Self::IdentityKey => "underlying group element is the group identity",
        })
    }
}

#[cfg(feature = "std")]
impl std::error::Error for PublicKeyConversionError {}

impl<G: Group> ops::Add<Self> for PublicKey<G> {
    type Output = Self;

    fn add(self, rhs: Self) -> Self {
        let element = self.element + rhs.element;
        Self::from_element(element)
    }
}

impl<G: Group> ops::Mul<&G::Scalar> for PublicKey<G> {
    type Output = Self;

    fn mul(self, k: &G::Scalar) -> Self {
        let element = self.element * k;
        Self::from_element(element)
    }
}

impl<G: Group> ops::Mul<u64> for PublicKey<G> {
    type Output = Self;

    fn mul(self, k: u64) -> Self {
        self * &G::Scalar::from(k)
    }
}

/// Keypair for ElGamal encryption and related protocols, consisting of a [`SecretKey`]
/// and the matching [`PublicKey`].
pub struct Keypair<G: Group> {
    secret: SecretKey<G>,
    public: PublicKey<G>,
}

impl<G: Group> fmt::Debug for Keypair<G> {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Keypair")
            .field("public", &self.public)
            .finish_non_exhaustive()
    }
}

impl<G: Group> Clone for Keypair<G> {
    fn clone(&self) -> Self {
        Keypair {
            secret: self.secret.clone(),
            public: self.public.clone(),
        }
    }
}

impl<G: Group> Keypair<G> {
    /// Generates a random keypair.
    pub fn generate<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
        let secret = SecretKey::generate(rng);
        Keypair {
            public: PublicKey::from(&secret),
            secret,
        }
    }

    /// Returns the public part of this keypair.
    pub fn public(&self) -> &PublicKey<G> {
        &self.public
    }

    /// Returns the secret part of this keypair.
    pub fn secret(&self) -> &SecretKey<G> {
        &self.secret
    }

    /// Returns public and secret keys comprising this keypair.
    pub fn into_tuple(self) -> (PublicKey<G>, SecretKey<G>) {
        (self.public, self.secret)
    }
}

impl<G: Group> From<SecretKey<G>> for Keypair<G> {
    fn from(secret: SecretKey<G>) -> Self {
        Self {
            public: PublicKey::from(&secret),
            secret,
        }
    }
}

impl<G: Group> ops::Mul<&G::Scalar> for Keypair<G> {
    type Output = Self;

    fn mul(self, k: &G::Scalar) -> Self {
        Keypair {
            secret: self.secret * k,
            public: self.public * k,
        }
    }
}