navajo 0.0.2

cryptographic APIs
Documentation
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
#![doc = include_str!("./aead/README.md")]
mod algorithm;
mod cipher;
mod ciphertext_info;
mod decryptor;
mod encryptor;
mod key_info;
mod material;
mod method;
mod nonce;
mod seed;
mod segment;
mod size;
mod stream;
mod try_stream;
use crate::{
    envelope,
    error::{EncryptError, KeyNotFoundError, RemoveKeyError},
    key::Key,
    keyring::Keyring,
    rand::Rng,
    Buffer, Envelope, Metadata, Origin, Status, SystemRng,
};
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
use alloc::{boxed::Box, sync::Arc};
use core::mem;
use futures::{Stream, TryStream};
pub(crate) use material::Material;
use size::Size;
use zeroize::ZeroizeOnDrop;

pub use crate::aad::Aad;

pub use algorithm::Algorithm;
pub use ciphertext_info::CiphertextInfo;
pub use decryptor::Decryptor;
pub use encryptor::Encryptor;
pub use key_info::AeadKeyInfo;
pub use method::Method;
pub use segment::Segment;
pub use stream::{AeadStream, DecryptStream, EncryptStream};
pub use try_stream::{AeadTryStream, DecryptTryStream, EncryptTryStream};

#[cfg(feature = "std")]
mod reader;
#[cfg(feature = "std")]
mod writer;
#[cfg(feature = "std")]
pub use reader::DecryptReader;
#[cfg(feature = "std")]
pub use writer::EncryptWriter;

/// Authenticated Encryption with Associated Data (AEAD)
#[derive(Clone, Debug, ZeroizeOnDrop)]
pub struct Aead {
    keyring: Keyring<Material>,
}
impl Aead {
    /// Creates a new AEAD keyring with a single key of the given algorithm with
    /// the provided metadata.
    pub fn new(algorithm: Algorithm, metadata: Option<Metadata>) -> Self {
        Self::create(&SystemRng, algorithm, metadata)
    }

    #[cfg(test)]
    pub fn new_with_rng<N>(rng: &N, algorithm: Algorithm, metadata: Option<Metadata>) -> Self
    where
        N: Rng,
    {
        Self::create(rng, algorithm, metadata)
    }
    /// Encrypts the given plaintext with `aad` as additional authenticated
    /// data. The resulting ciphertext replaces the contents of `plaintext`.
    /// Note that `aad` is not encrypted and is merely used for authentication.
    /// As such, there are no secrecy gaurantees for `aad`.
    ///
    /// # Errors
    /// Returns an [`EncryptError`] under the following conditions:
    /// - `plaintext` is empty
    /// - the backend fails to encrypt the plaintext
    ///
    /// # Example
    /// ```
    /// use navajo::aead::{Aead, Algorithm};
    /// use navajo::Aad;
    /// let aead = Aead::new(Algorithm::Aes256Gcm, None);
    /// let mut data = b"Hello, world!".to_vec();
    /// aead.encrypt_in_place(Aad::empty(), &mut data).unwrap();
    /// assert_ne!(&data, &b"Hello, world!");
    /// ```
    pub fn encrypt_in_place<A, T>(&self, aad: Aad<A>, plaintext: &mut T) -> Result<(), EncryptError>
    where
        A: AsRef<[u8]>,
        T: Buffer,
    {
        let encryptor = Encryptor::new(SystemRng, self, None, mem::take(plaintext));
        let result = encryptor
            .finalize(aad)?
            .next()
            .ok_or(EncryptError::Unspecified)?;
        *plaintext = result;
        Ok(())
    }
    /// Encrypts the given plaintext with `aad` as additional authenticated
    /// data. The resulting ciphertext is returned. Note that `aad` is not
    /// encrypted and is merely used for authentication. As such, there are no
    /// secrecy gaurantees for `aad`.
    ///
    /// # Errors
    /// Returns an [`EncryptError`] under the following conditions:
    /// - `plaintext` is empty
    /// - the backend fails to encrypt the plaintext
    ///
    /// # Example
    /// ```
    /// use navajo::aead::{Aead, Algorithm};
    /// use navajo::Aad;
    /// let aead = Aead::new(Algorithm::Aes256Gcm, None);
    /// let mut data = b"Hello, world!".to_vec();
    /// let ciphertext = aead.encrypt(Aad::empty(), &mut data).unwrap();
    /// assert_ne!(&data, &ciphertext);
    /// ```
    pub fn encrypt<A, T>(&self, aad: Aad<A>, plaintext: T) -> Result<Vec<u8>, EncryptError>
    where
        A: AsRef<[u8]>,
        T: AsRef<[u8]>,
    {
        let encryptor = Encryptor::new(SystemRng, self, None, plaintext.as_ref().to_vec());
        let result = encryptor
            .finalize(aad)?
            .next()
            .ok_or(EncryptError::Unspecified)?;
        Ok(result)
    }

    /// Returns a new [`EncryptStream`] which encrypts data using either STREAM
    /// as desribed in [Online Authenticated-Encryption and its Nonce-Reuse
    /// Misuse-Resistance](https://eprint.iacr.org/2015/189.pdf) if the
    /// finalized ciphertext is greater than the specified [`Segment`] as
    /// described in [RFC 5116](https://tools.ietf.org/html/rfc5116) with an 5
    /// byte header. Otherwise traditional "online" AEAD encryption is used.
    ///
    /// [`Aad`] `aad` is used for authentication and is not encrypted. As such, there
    /// are no secrecy gaurantees for `aad`.
    ///
    /// If the resulting ciphertext is greater than [`Segment`], the header will
    /// be in the form:
    ///
    /// ```plaintext
    /// || Method (1) || Key Id (4) || Salt (variable) || Nonce Prefix (variable) ||
    /// ```
    /// where `Salt` is the length of the algorithm's key and `Nonce Prefix` is
    /// the length of the algorithm's nonce minus 5 bytes (4 for the segment
    /// counter & 1 byte for the last-block flag).
    ///
    /// If the resulting ciphertext is less than [`Segment`], the header will be
    /// in the form:
    /// ```plaintext
    /// || Method (1) || Key Id (4) || Nonce (variable) ||
    /// ```
    ///
    /// If the resulting ciphertext is greater than [`Segment`] then each
    /// segment block will be be of the size specified by [`Segment`] except for
    /// the last, which will be no greater than [`Segment`].
    ///
    /// # Example
    /// ```
    /// use navajo::aead::{Aead, Algorithm, Segment};
    /// use navajo::Aad;
    /// use futures::{stream, TryStreamExt};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let aead = Aead::new(Algorithm::ChaCha20Poly1305, None);
    ///     let data = stream::iter(vec![
    ///         Vec::from("hello".as_bytes()),
    ///         Vec::from(" ".as_bytes()),
    ///         Vec::from("world".as_bytes()),
    ///     ]);
    ///     let enc_stream = aead.encrypt_stream(data, Aad::empty(), Segment::FourKilobytes);
    ///     let ciphertext: Vec<u8> = enc_stream.try_concat().await.unwrap();
    ///     assert_ne!(&ciphertext, &b"hello world");
    /// }
    pub fn encrypt_stream<S, A>(
        &self,
        stream: S,
        aad: Aad<A>,
        segment: Segment,
    ) -> EncryptStream<S, A>
    where
        S: Stream,
        S::Item: AsRef<[u8]>,
        A: AsRef<[u8]> + Send + Sync,
    {
        EncryptStream::new(SystemRng, stream, segment, aad, self)
    }

    pub fn encrypt_try_stream<S, A>(
        &self,
        stream: S,
        segment: Segment,
        aad: Aad<A>,
    ) -> EncryptTryStream<S, A>
    where
        S: TryStream,
        S::Ok: AsRef<[u8]>,
        S::Error: Send + Sync,
        A: AsRef<[u8]> + Send + Sync,
    {
        EncryptTryStream::new(SystemRng, stream, segment, aad, self)
    }

    #[cfg(feature = "std")]
    pub fn encrypt_writer<'w, F, W, A>(
        &self,
        writer: &'w mut W,
        aad: Aad<A>,
        segment: Segment,
        f: F,
    ) -> Result<usize, std::io::Error>
    where
        F: FnOnce(&mut EncryptWriter<'w, W, A>) -> Result<(), std::io::Error>,
        W: std::io::Write,
        A: 'w + AsRef<[u8]>,
    {
        let mut writer = EncryptWriter::new(SystemRng, writer, segment, aad, self);
        f(&mut writer)?;
        writer.finalize()
    }

    pub fn decrypt<A, T>(
        &self,
        aad: Aad<A>,
        ciphertext: T,
    ) -> Result<Vec<u8>, crate::error::DecryptError>
    where
        A: AsRef<[u8]>,
        T: AsRef<[u8]>,
    {
        let data = ciphertext.as_ref().to_vec();
        let decryptor = Decryptor::new(self, data);
        let mut result = Vec::new();
        for segment in decryptor.finalize(aad)? {
            result.extend_from_slice(&segment);
        }
        Ok(result)
    }

    pub fn decrypt_in_place<A, T>(
        &self,
        aad: Aad<A>,
        ciphertext: &mut T,
    ) -> Result<(), crate::error::DecryptError>
    where
        A: AsRef<[u8]>,
        T: Buffer,
    {
        let decryptor = Decryptor::new(self, mem::take(ciphertext));
        let result = decryptor
            .finalize(aad)?
            .next()
            .ok_or(crate::error::DecryptError::Unspecified)?;
        *ciphertext = result;
        Ok(())
    }
    pub fn decrypt_stream<S, A>(&self, stream: S, aad: Aad<A>) -> DecryptStream<S, Self, A>
    where
        S: Stream,
        S::Item: AsRef<[u8]>,
        A: AsRef<[u8]> + Send + Sync,
    {
        DecryptStream::new(SystemRng, stream, self.clone(), aad)
    }

    pub fn decrypt_try_stream<S, A>(&self, stream: S, aad: Aad<A>) -> DecryptTryStream<S, Self, A>
    where
        S: TryStream,
        S::Ok: AsRef<[u8]>,
        S::Error: Send + Sync,
        A: AsRef<[u8]> + Send + Sync,
    {
        DecryptTryStream::new(stream, self.clone(), aad)
    }

    #[cfg(feature = "std")]
    pub fn decrypt_reader<N, A>(&self, reader: N, aad: Aad<A>) -> DecryptReader<N, A, &Self>
    where
        N: std::io::Read,
        A: AsRef<[u8]>,
    {
        DecryptReader::new(reader, aad, self)
    }

    pub(crate) fn from_keyring(keyring: Keyring<Material>) -> Self {
        Self { keyring }
    }

    /// Returns a [`Vec`] containing [`AeadKeyInfo`] for each key in this
    /// keyring.
    pub fn keys(&self) -> Vec<AeadKeyInfo> {
        self.keyring.keys().iter().map(AeadKeyInfo::new).collect()
    }

    /// Returns [`AeadKeyInfo`] for the primary key.
    pub fn primary_key(&self) -> AeadKeyInfo {
        self.keyring.primary().into()
    }

    pub fn promote(
        &mut self,
        key_id: impl Into<u32>,
    ) -> Result<AeadKeyInfo, crate::error::KeyNotFoundError> {
        self.keyring.promote(key_id).map(AeadKeyInfo::new)
    }

    pub fn add(&mut self, algorithm: Algorithm, metadata: Option<Metadata>) -> AeadKeyInfo {
        let id = self.keyring.next_id(&SystemRng);
        let metadata = metadata.map(Arc::new);
        let material = Material::generate(&SystemRng, algorithm);
        let key = Key::new(id, Status::Secondary, Origin::Navajo, material, metadata);
        let info = AeadKeyInfo::new(&key);
        self.keyring.add(key);
        info
    }
    pub fn disable(
        &mut self,
        key_id: impl Into<u32>,
    ) -> Result<AeadKeyInfo, crate::error::DisableKeyError<Algorithm>> {
        self.keyring.disable(key_id).map(AeadKeyInfo::new)
    }

    pub fn enable(&mut self, key_id: impl Into<u32>) -> Result<AeadKeyInfo, KeyNotFoundError> {
        self.keyring.enable(key_id).map(AeadKeyInfo::new)
    }

    pub fn delete(
        &mut self,
        key_id: impl Into<u32>,
    ) -> Result<AeadKeyInfo, RemoveKeyError<Algorithm>> {
        self.keyring.remove(key_id).map(|k| AeadKeyInfo::new(&k))
    }

    pub fn update_key_meta(
        &mut self,
        key_id: impl Into<u32>,
        meta: Option<Metadata>,
    ) -> Result<AeadKeyInfo, KeyNotFoundError> {
        self.keyring
            .update_key_metadata(key_id, meta)
            .map(AeadKeyInfo::new)
    }

    pub(crate) fn keyring(&self) -> &Keyring<Material> {
        &self.keyring
    }

    fn create<N>(rng: &N, algorithm: Algorithm, metadata: Option<Metadata>) -> Self
    where
        N: Rng,
    {
        let id = rng.u32().unwrap();
        let material = Material::generate(rng, algorithm);
        let metadata = metadata.map(Arc::new);
        let key = Key::new(id, Status::Primary, Origin::Navajo, material, metadata);
        let keyring = Keyring::new(key);
        Self { keyring }
    }

    pub fn set_key_metadata(
        &mut self,
        key_id: u32,
        metadata: Option<Metadata>,
    ) -> Result<AeadKeyInfo, KeyNotFoundError> {
        self.keyring.update_key_metadata(key_id, metadata)?;
        let key = self.keyring.get(key_id)?;
        Ok(AeadKeyInfo::new(key))
    }
}

impl AsMut<Aead> for Aead {
    fn as_mut(&mut self) -> &mut Aead {
        self
    }
}

impl Envelope for Aead {
    type EncryptError = crate::error::EncryptError;
    type DecryptError = crate::error::DecryptError;

    fn encrypt_dek<'a, A, P>(
        &'a self,
        aad: Aad<A>,
        plaintext: P,
    ) -> core::pin::Pin<
        Box<dyn futures::Future<Output = Result<Vec<u8>, Self::EncryptError>> + Send + '_>,
    >
    where
        A: 'static + AsRef<[u8]> + Send + Sync,
        P: 'static + AsRef<[u8]> + Send + Sync,
    {
        Box::pin(async move { self.encrypt(aad, plaintext) })
    }

    fn decrypt_dek<'a, A, B>(
        &'a self,
        aad: Aad<A>,
        ciphertext: B,
    ) -> core::pin::Pin<
        Box<dyn futures::Future<Output = Result<Vec<u8>, Self::DecryptError>> + Send + '_>,
    >
    where
        A: 'static + AsRef<[u8]> + Send + Sync,
        B: 'static + AsRef<[u8]> + Send + Sync,
    {
        Box::pin(async move { self.decrypt(aad, ciphertext) })
    }
}

impl envelope::sync::Envelope for Aead {
    type EncryptError = crate::error::EncryptError;
    type DecryptError = crate::error::DecryptError;
    fn encrypt_dek<A, P>(&self, aad: Aad<A>, plaintext: P) -> Result<Vec<u8>, Self::EncryptError>
    where
        A: AsRef<[u8]>,
        P: AsRef<[u8]>,
    {
        self.encrypt(aad, plaintext)
    }
    fn decrypt_dek<A, C>(&self, aad: Aad<A>, ciphertext: C) -> Result<Vec<u8>, Self::DecryptError>
    where
        A: AsRef<[u8]>,
        C: AsRef<[u8]>,
    {
        self.decrypt(aad, ciphertext)
    }
}

impl AsRef<Aead> for Aead {
    fn as_ref(&self) -> &Aead {
        self
    }
}

#[cfg(test)]
mod tests {
    use quickcheck_macros::quickcheck;
    use strum::IntoEnumIterator;

    use super::*;

    #[quickcheck]
    fn encrypt_decrypt(mut plaintext: Vec<u8>, aad: Vec<u8>) -> bool {
        for algorithm in Algorithm::iter() {
            let src = plaintext.clone();
            let aead = Aead::new(algorithm, None);
            let result = aead.encrypt_in_place(Aad(&aad), &mut plaintext);
            if plaintext.is_empty() {
                if result.is_ok() {
                    return false;
                } else {
                    continue;
                }
            }
            if aead.decrypt_in_place(Aad(&aad), &mut plaintext).is_err() {
                return false;
            }
            if src != plaintext {
                return false;
            }
        }
        true
    }

    #[test]
    fn test_encrypt_in_place() {
        let aead = Aead::new(Algorithm::Aes256Gcm, None);
        let mut data = b"hello world".to_vec();
        aead.encrypt_in_place(Aad(b"additional data"), &mut data)
            .unwrap();
        assert_ne!(data, b"hello world");
        assert!(!data.is_empty());
    }
    #[test]
    fn test_decrypt_in_place() {
        let aead = Aead::new(Algorithm::Aes256Gcm, None);
        let mut data = b"hello world".to_vec();
        aead.encrypt_in_place(Aad(b"additional data"), &mut data)
            .unwrap();
        let aead = Aead::new(Algorithm::Aes256Gcm, None);
        let mut data = b"hello world".to_vec();
        aead.encrypt_in_place(Aad(b"additional data"), &mut data)
            .unwrap();
        assert_ne!(data, b"hello world");
        aead.decrypt_in_place(Aad(b"additional data"), &mut data)
            .unwrap();
        assert_eq!(data, b"hello world");
    }
    #[cfg(feature = "std")]
    #[test]
    fn test_encrypt_writer() {
        use std::io::Write;

        let mut writer = vec![];
        let aad = Aad(b"additional data");
        let aead = Aead::new(Algorithm::Aes256Gcm, None);
        let msg = b"hello world".to_vec();
        aead.encrypt_writer(&mut writer, Aad(aad), Segment::FourKilobytes, |w| {
            w.write_all(&msg)
        })
        .unwrap();

        let decryptor = Decryptor::new(&aead, writer);
        let result = decryptor.finalize(aad).unwrap().next().unwrap();
        assert_eq!(result, msg);
    }
}