Skip to main content

jf_aead/
lib.rs

1// Copyright (c) 2022 Espresso Systems (espressosys.com)
2// This file is part of the Jellyfish library.
3
4// You should have received a copy of the MIT License
5// along with the Jellyfish library. If not, see <https://mit-license.org/>.
6
7//! Use `crypto_kx` to derive shared session secrets and use symmetric AEAD
8//! (`xchacha20poly1305`) for authenticated encryption with associated data.
9//!
10//! We only provide an ultra-thin wrapper for stable APIs for jellyfish users,
11//! independent of RustCrypto's upstream changes.
12
13#![cfg_attr(not(feature = "std"), no_std)]
14#![deny(missing_docs)]
15#[cfg(test)]
16extern crate std;
17
18#[cfg(any(not(feature = "std"), target_has_atomic = "ptr"))]
19#[doc(hidden)]
20extern crate alloc;
21
22use ark_serialize::*;
23use ark_std::{
24    fmt,
25    ops::{Deref, DerefMut},
26    rand::{CryptoRng, RngCore},
27    vec::Vec,
28};
29use chacha20poly1305::{
30    aead::{Aead, AeadCore, Payload},
31    KeyInit, XChaCha20Poly1305, XNonce,
32};
33use displaydoc::Display;
34use serde::{Deserialize, Deserializer, Serialize};
35
36#[derive(Clone, Eq, PartialEq, Serialize, Deserialize, Hash)]
37/// Public/encryption key for AEAD
38pub struct EncKey(crypto_kx::PublicKey);
39
40impl From<[u8; 32]> for EncKey {
41    fn from(bytes: [u8; 32]) -> Self {
42        Self(crypto_kx::PublicKey::from(bytes))
43    }
44}
45impl From<EncKey> for [u8; 32] {
46    fn from(enc_key: EncKey) -> Self {
47        *enc_key.0.as_ref()
48    }
49}
50impl From<DecKey> for EncKey {
51    fn from(dec_key: DecKey) -> Self {
52        let enc_key = *crypto_kx::Keypair::from(dec_key.0).public();
53        Self(enc_key)
54    }
55}
56impl Default for EncKey {
57    fn default() -> Self {
58        Self(crypto_kx::PublicKey::from(
59            [0u8; crypto_kx::PublicKey::BYTES],
60        ))
61    }
62}
63impl fmt::Debug for EncKey {
64    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
65        f.debug_tuple("aead::EncKey")
66            .field(self.0.as_ref())
67            .finish()
68    }
69}
70
71/// AEAD Error.
72// This type is deliberately opaque as in `crypto_kx`.
73#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Display)]
74pub struct AEADError;
75
76impl ark_std::error::Error for AEADError {}
77
78impl EncKey {
79    /// Encrypt a message with authenticated associated data which is an
80    /// optional bytestring which is not encrypted, but is authenticated
81    /// along with the message. Failure to pass the same AAD that was used
82    /// during encryption will cause decryption to fail, which is useful if you
83    /// would like to "bind" the ciphertext to some identifier, like a
84    /// digital signature key.
85    pub fn encrypt(
86        &self,
87        mut rng: impl RngCore + CryptoRng,
88        message: &[u8],
89        aad: &[u8],
90    ) -> Result<Ciphertext, AEADError> {
91        // generate an ephemeral key pair as the virtual sender to derive the
92        // crypto box
93        let ephemeral_keypair = crypto_kx::Keypair::generate(&mut rng);
94        // `crypto_kx` generates a pair of shared secrets, see <https://libsodium.gitbook.io/doc/key_exchange>
95        // we use the transmission key of the ephemeral sender (equals to the
96        // receiving key of the server) as the shared secret.
97        let shared_secret = ephemeral_keypair.session_keys_to(&self.0).tx;
98        let cipher = XChaCha20Poly1305::new(shared_secret.as_ref().into());
99        let nonce = XChaCha20Poly1305::generate_nonce(&mut rng);
100
101        // encrypt the message and associated data using crypto box
102        let ct = cipher
103            .encrypt(&nonce, Payload { msg: message, aad })
104            .map_err(|_| AEADError)?;
105
106        Ok(Ciphertext {
107            nonce: Nonce(nonce),
108            ct,
109            ephemeral_pk: EncKey(*ephemeral_keypair.public()),
110        })
111    }
112}
113
114/// Private/decryption key for AEAD
115// look into zeroization logic from aead lib
116#[derive(Clone, Serialize, Deserialize)]
117struct DecKey(crypto_kx::SecretKey);
118
119impl From<[u8; 32]> for DecKey {
120    fn from(bytes: [u8; 32]) -> Self {
121        Self(crypto_kx::SecretKey::from(bytes))
122    }
123}
124impl From<DecKey> for [u8; 32] {
125    fn from(dec_key: DecKey) -> Self {
126        dec_key.0.to_bytes()
127    }
128}
129
130impl Default for DecKey {
131    fn default() -> Self {
132        Self(crypto_kx::SecretKey::from([0; crypto_kx::SecretKey::BYTES]))
133    }
134}
135impl fmt::Debug for DecKey {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        f.debug_tuple("aead::DecKey")
138            .field(&self.0.to_bytes())
139            .finish()
140    }
141}
142
143/// Keypair for Authenticated Encryption with Associated Data
144#[derive(
145    Clone, Debug, Default, Serialize, Deserialize, CanonicalSerialize, CanonicalDeserialize,
146)]
147pub struct KeyPair {
148    enc_key: EncKey,
149    dec_key: DecKey,
150}
151
152impl PartialEq for KeyPair {
153    fn eq(&self, other: &KeyPair) -> bool {
154        self.enc_key == other.enc_key
155    }
156}
157
158impl KeyPair {
159    /// Randomly sample a key pair.
160    pub fn generate<R: RngCore + CryptoRng>(rng: &mut R) -> Self {
161        let (enc_key, dec_key) = crypto_kx::Keypair::generate(rng).split();
162        Self {
163            enc_key: EncKey(enc_key),
164            dec_key: DecKey(dec_key),
165        }
166    }
167
168    /// Getter for the public/encryption key
169    pub fn enc_key(&self) -> EncKey {
170        self.enc_key.clone()
171    }
172
173    /// Getter for reference to the public/encryption key
174    pub fn enc_key_ref(&self) -> &EncKey {
175        &self.enc_key
176    }
177
178    /// Decrypt a ciphertext with authenticated associated data provided.
179    /// If the associated data is different that that used during encryption,
180    /// then decryption will fail.
181    pub fn decrypt(&self, ciphertext: &Ciphertext, aad: &[u8]) -> Result<Vec<u8>, AEADError> {
182        let shared_secret = crypto_kx::Keypair::from(self.dec_key.0.clone())
183            .session_keys_from(&ciphertext.ephemeral_pk.0)
184            .rx;
185        let cipher = XChaCha20Poly1305::new(shared_secret.as_ref().into());
186        let plaintext = cipher
187            .decrypt(
188                &ciphertext.nonce,
189                Payload {
190                    msg: &ciphertext.ct,
191                    aad,
192                },
193            )
194            .map_err(|_| AEADError)?;
195        Ok(plaintext)
196    }
197}
198// newtype for `chacha20poly1305::XNonce` for easier serde support for
199// `Ciphertext`.
200#[derive(Clone, Debug, PartialEq, Eq, Hash)]
201struct Nonce(XNonce);
202
203impl Serialize for Nonce {
204    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
205    where
206        S: serde::Serializer,
207    {
208        serializer.serialize_bytes(self.0.as_slice())
209    }
210}
211
212impl<'de> Deserialize<'de> for Nonce {
213    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
214    where
215        D: Deserializer<'de>,
216    {
217        struct NonceVisitor;
218
219        impl<'de> serde::de::Visitor<'de> for NonceVisitor {
220            type Value = Nonce;
221
222            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
223                formatter.write_str("byte array")
224            }
225
226            fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
227            where
228                E: serde::de::Error,
229            {
230                Ok(Nonce(*XNonce::from_slice(&v)))
231            }
232
233            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
234            where
235                A: serde::de::SeqAccess<'de>,
236            {
237                let bytes: Vec<u8> = seq
238                    .next_element()?
239                    .ok_or_else(|| serde::de::Error::invalid_length(0, &self))?;
240                Ok(Nonce(*XNonce::from_slice(&bytes)))
241            }
242        }
243
244        deserializer.deserialize_byte_buf(NonceVisitor)
245    }
246}
247
248// Deref for newtype which acts like a smart pointer
249impl Deref for Nonce {
250    type Target = XNonce;
251    fn deref(&self) -> &Self::Target {
252        &self.0
253    }
254}
255impl DerefMut for Nonce {
256    fn deref_mut(&mut self) -> &mut Self::Target {
257        &mut self.0
258    }
259}
260
261/// The ciphertext produced by AEAD encryption
262#[derive(
263    Clone,
264    Debug,
265    PartialEq,
266    Eq,
267    Hash,
268    Serialize,
269    Deserialize,
270    CanonicalSerialize,
271    CanonicalDeserialize,
272)]
273pub struct Ciphertext {
274    nonce: Nonce,
275    ct: Vec<u8>,
276    ephemeral_pk: EncKey,
277}
278
279// TODO: (alex) Temporarily add CanonicalSerde back to these structs due to the
280// limitations of `tagged` proc macro and requests from downstream usage.
281// Tracking issue: <https://github.com/EspressoSystems/jellyfish/issues/288>
282mod canonical_serde {
283    use super::*;
284
285    impl CanonicalSerialize for EncKey {
286        fn serialize_with_mode<W: Write>(
287            &self,
288            mut writer: W,
289            _compress: Compress,
290        ) -> Result<(), SerializationError> {
291            let bytes: [u8; crypto_kx::PublicKey::BYTES] = self.clone().into();
292            writer.write_all(&bytes)?;
293            Ok(())
294        }
295        fn serialized_size(&self, _compress: Compress) -> usize {
296            crypto_kx::PublicKey::BYTES
297        }
298    }
299
300    impl CanonicalDeserialize for EncKey {
301        fn deserialize_with_mode<R: Read>(
302            mut reader: R,
303            _compress: Compress,
304            _validate: Validate,
305        ) -> Result<Self, SerializationError> {
306            let mut result = [0u8; crypto_kx::PublicKey::BYTES];
307            reader.read_exact(&mut result)?;
308            Ok(EncKey(crypto_kx::PublicKey::from(result)))
309        }
310    }
311
312    impl Valid for EncKey {
313        fn check(&self) -> Result<(), SerializationError> {
314            Ok(())
315        }
316    }
317
318    impl CanonicalSerialize for DecKey {
319        fn serialize_with_mode<W: Write>(
320            &self,
321            mut writer: W,
322            _compress: Compress,
323        ) -> Result<(), SerializationError> {
324            let bytes: [u8; crypto_kx::SecretKey::BYTES] = self.clone().into();
325            writer.write_all(&bytes)?;
326            Ok(())
327        }
328        fn serialized_size(&self, _compress: Compress) -> usize {
329            crypto_kx::SecretKey::BYTES
330        }
331    }
332
333    impl CanonicalDeserialize for DecKey {
334        fn deserialize_with_mode<R: Read>(
335            mut reader: R,
336            _compress: Compress,
337            _validate: Validate,
338        ) -> Result<Self, SerializationError> {
339            let mut result = [0u8; crypto_kx::SecretKey::BYTES];
340            reader.read_exact(&mut result)?;
341            Ok(DecKey(crypto_kx::SecretKey::from(result)))
342        }
343    }
344    impl Valid for DecKey {
345        fn check(&self) -> Result<(), SerializationError> {
346            Ok(())
347        }
348    }
349
350    impl CanonicalSerialize for Nonce {
351        fn serialize_with_mode<W: Write>(
352            &self,
353            mut writer: W,
354            _compress: Compress,
355        ) -> Result<(), SerializationError> {
356            writer.write_all(self.0.as_slice())?;
357            Ok(())
358        }
359        fn serialized_size(&self, _compress: Compress) -> usize {
360            // see <https://docs.rs/chacha20poly1305/0.10.1/chacha20poly1305/type.XNonce.html>
361            24
362        }
363    }
364
365    impl CanonicalDeserialize for Nonce {
366        fn deserialize_with_mode<R: Read>(
367            mut reader: R,
368            _compress: Compress,
369            _validate: Validate,
370        ) -> Result<Self, SerializationError> {
371            let mut result = [0u8; 24];
372            reader.read_exact(&mut result)?;
373            Ok(Nonce(XNonce::from(result)))
374        }
375    }
376    impl Valid for Nonce {
377        fn check(&self) -> Result<(), SerializationError> {
378            Ok(())
379        }
380    }
381}
382
383#[cfg(test)]
384mod test {
385    use super::*;
386    use ark_std::rand::SeedableRng;
387    use rand_chacha::ChaCha20Rng;
388
389    #[test]
390    fn test_aead_encryption() -> Result<(), AEADError> {
391        let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
392        let keypair1 = KeyPair::generate(&mut rng);
393        let keypair2 = KeyPair::generate(&mut rng);
394        let msg = b"The quick brown fox jumps over the lazy dog".to_vec();
395        let aad = b"my associated data".to_vec();
396
397        // check correctness
398        let ct1 = keypair1.enc_key.encrypt(&mut rng, &msg, &aad)?;
399        assert!(keypair1.decrypt(&ct1, &aad).is_ok());
400        let plaintext1 = keypair1.decrypt(&ct1, &aad)?;
401        assert!(msg == plaintext1);
402
403        // check soundness
404        assert!(keypair2.decrypt(&ct1, &aad).is_err());
405        assert!(keypair1.decrypt(&ct1, b"wrong associated data").is_err());
406        let ct2 = keypair1.enc_key.encrypt(&mut rng, b"wrong message", &aad)?;
407        let plaintext2 = keypair1.decrypt(&ct2, &aad)?;
408        assert!(msg != plaintext2);
409
410        // rng or nounce shouldn't affect decryption
411        let rng = ChaCha20Rng::from_seed([1u8; 32]);
412        let ct3 = keypair1.enc_key.encrypt(rng, &msg, &aad)?;
413        assert!(keypair1.decrypt(&ct3, &aad).is_ok());
414        let plaintext3 = keypair1.decrypt(&ct3, &aad)?;
415        assert!(msg == plaintext3);
416
417        Ok(())
418    }
419
420    #[test]
421    fn test_serde() {
422        let mut rng = jf_utils::test_rng();
423        let keypair = KeyPair::generate(&mut rng);
424        let msg = b"The quick brown fox jumps over the lazy dog".to_vec();
425        let aad = b"my associated data".to_vec();
426        let ciphertext = keypair.enc_key.encrypt(&mut rng, &msg, &aad).unwrap();
427
428        // serde for Keypair
429        let bytes = bincode::serialize(&keypair).unwrap();
430        assert_eq!(keypair, bincode::deserialize(&bytes).unwrap());
431        // wrong byte length
432        assert!(bincode::deserialize::<KeyPair>(&bytes[1..]).is_err());
433
434        // serde for EncKey
435        let bytes = bincode::serialize(keypair.enc_key_ref()).unwrap();
436        assert_eq!(
437            keypair.enc_key_ref(),
438            &bincode::deserialize(&bytes).unwrap()
439        );
440        // wrong byte length
441        assert!(bincode::deserialize::<EncKey>(&bytes[1..]).is_err());
442
443        // serde for DecKey
444        let bytes = bincode::serialize(&keypair.dec_key).unwrap();
445        assert_eq!(
446            keypair.dec_key.0.to_bytes(),
447            bincode::deserialize::<DecKey>(&bytes).unwrap().0.to_bytes()
448        );
449        // wrong byte length
450        assert!(bincode::deserialize::<DecKey>(&bytes[1..]).is_err());
451
452        // serde for Ciphertext
453        let bytes = bincode::serialize(&ciphertext).unwrap();
454        assert_eq!(&ciphertext, &bincode::deserialize(&bytes).unwrap());
455        // wrong byte length
456        assert!(bincode::deserialize::<Ciphertext>(&bytes[1..]).is_err());
457    }
458
459    #[test]
460    fn test_canonical_serde() {
461        let mut rng = jf_utils::test_rng();
462        let keypair = KeyPair::generate(&mut rng);
463        let msg = b"The quick brown fox jumps over the lazy dog".to_vec();
464        let aad = b"my associated data".to_vec();
465        let ciphertext = keypair.enc_key.encrypt(&mut rng, &msg, &aad).unwrap();
466
467        // when testing keypair, already tests serde on pk and sk
468        let mut bytes = Vec::new();
469        CanonicalSerialize::serialize_compressed(&keypair, &mut bytes).unwrap();
470        assert_eq!(
471            keypair,
472            KeyPair::deserialize_compressed(&bytes[..]).unwrap()
473        );
474        assert!(KeyPair::deserialize_compressed(&bytes[..bytes.len() - 1]).is_err());
475
476        let mut bytes = Vec::new();
477        CanonicalSerialize::serialize_compressed(&ciphertext, &mut bytes).unwrap();
478        assert_eq!(
479            ciphertext,
480            Ciphertext::deserialize_compressed(&bytes[..]).unwrap()
481        );
482        assert!(Ciphertext::deserialize_compressed(&bytes[..bytes.len() - 1]).is_err());
483    }
484}