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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
#![doc = include_str!("./aead/README.md")]
mod algorithm;
mod backend;
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, OpenError, RemoveKeyError, SealError},
key::Key,
keyring::Keyring,
rand::Rng,
Buffer, Envelope, Metadata, Origin, Primitive, Status, SystemRng,
};
use alloc::boxed::Box;
#[cfg(not(feature = "std"))]
use alloc::vec::Vec;
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 self::key_info::{KeyInfo, KeyringInfo};
pub use algorithm::Algorithm;
pub use ciphertext_info::CiphertextInfo;
pub use decryptor::Decryptor;
pub use encryptor::Encryptor;
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 {
/// Opens an [`Aead`] keyring from the given `data` and validates the
/// authenticity with `aad` by means of the [`Envelope`] `envelope`.
///
/// # Errors
/// Errors if the keyring could not be opened by the or the authenticity
/// could not be verified by the [`Envelope`] using futures.
///
/// # Example
/// ```rust
/// use navajo::Aad;
/// use navajo::aead::{ Aead, Algorithm };
/// use navajo::envelope::InMemory;
///
/// #[tokio::main]
/// async fn main() {
/// let aead = Aead::new(Algorithm::ChaCha20Poly1305, None);
/// let primary_key = aead.primary_key();
/// // in a real application, you would use a real key management service.
/// // InMemory is only suitable for testing.
/// let in_mem = InMemory::default();
/// let data = Aead::seal(Aad::empty(), &aead, &in_mem).await.unwrap();
/// let aead = Aead::open(Aad::empty(), data, &in_mem).await.unwrap();
/// assert_eq!(aead.primary_key(), primary_key);
/// }
/// ```
pub async fn open<A, D, E>(aad: Aad<A>, data: D, envelope: &E) -> Result<Self, OpenError>
where
E: 'static + Envelope,
D: 'static + AsRef<[u8]> + Send + Sync,
A: 'static + AsRef<[u8]> + Send + Sync,
{
let primitive = Primitive::open(aad, data, envelope).await?;
primitive
.aead()
.ok_or(OpenError("primitive is not Aead".into()))
}
/// Opens an [`Aead`] keyring from the given `data` and validates the
/// authenticity with `aad` by means of the [`Envelope`] using
/// blocking APIs.
///
/// # Errors
/// Errors if the keyring could not be opened by the or the authenticity
/// could not be verified by the [`Envelope`].
///
/// # Example
/// ```rust
/// use navajo::Aad;
/// use navajo::aead::{ Aead, Algorithm };
/// use navajo::envelope::InMemory;
///
/// let aead = Aead::new(Algorithm::Aes256Gcm, None);
/// let primary_key = aead.primary_key();
/// // in a real application, you would use a real key management service.
/// // InMemory is only suitable for testing.
/// let in_mem = InMemory::default();
/// let data = Aead::seal_sync(Aad(&b"associated data"), &aead, &in_mem).unwrap();
/// let aead = Aead::open_sync(Aad(&b"associated data"), &data, &in_mem).unwrap();
/// assert_eq!(aead.primary_key(), primary_key);
/// ```
pub fn open_sync<A, E, C>(aad: Aad<A>, ciphertext: C, envelope: &E) -> Result<Self, OpenError>
where
A: AsRef<[u8]>,
C: AsRef<[u8]>,
E: 'static + crate::envelope::sync::Envelope,
{
let primitive = Primitive::open_sync(aad, ciphertext, envelope)?;
if let Some(aead) = primitive.aead() {
Ok(aead)
} else {
Err(OpenError("primitive is not a aead".into()))
}
}
/// Seals an [`Aead`] keyring and tags it with `aad` for future
/// authenticationby means of the [`Envelope`].
///
/// # Errors
/// Errors if the keyring could not be sealed by the [`Envelope`].
///
/// # Example
/// ```rust
/// use navajo::Aad;
/// use navajo::aead::{ Aead, Algorithm };
/// use navajo::envelope::InMemory;
///
/// #[tokio::main]
/// async fn main() {
/// let aead = Aead::new(Algorithm::Aes256Gcm, None);
/// let primary_key = aead.primary_key();
/// // in a real application, you would use a real key management service.
/// // InMemory is only suitable for testing.
/// let in_mem = InMemory::default();
/// let data = Aead::seal(Aad::empty(), &aead, &in_mem).await.unwrap();
/// let aead = Aead::open(Aad::empty(), data, &in_mem).await.unwrap();
/// assert_eq!(aead.primary_key(), primary_key);
/// }
/// ```
pub async fn seal<A, E>(aad: Aad<A>, aead: &Self, envelope: &E) -> Result<Vec<u8>, SealError>
where
A: 'static + AsRef<[u8]> + Send + Sync,
E: Envelope + 'static,
{
Primitive::Aead(aead.clone()).seal(aad, envelope).await
}
/// Seals a [`Aead`] keyring and tags it with `aad` for future
/// authenticationby means of the [`Envelope`].
///
/// # Errors
/// Errors if the keyring could not be sealed by the [`Envelope`].
///
/// # Example
/// ```rust
/// use navajo::Aad;
/// use navajo::aead::{ Aead, Algorithm };
/// use navajo::envelope::InMemory;
///
/// let aead = Aead::new(Algorithm::Aes256Gcm, None);
/// let primary_key = aead.primary_key();
/// // in a real application, you would use a real key management service.
/// // InMemory is only suitable for testing.
/// let in_mem = InMemory::default();
/// let ciphertext = Aead::seal_sync(Aad::empty(), &aead, &in_mem).unwrap();
/// let aead = Aead::open_sync(Aad::empty(), ciphertext, &in_mem).unwrap();
/// assert_eq!(aead.primary_key(), primary_key);
/// ```
pub fn seal_sync<A, E>(aad: Aad<A>, aead: &Self, envelope: &E) -> Result<Vec<u8>, SealError>
where
A: AsRef<[u8]>,
E: 'static + crate::envelope::sync::Envelope,
{
Primitive::Aead(aead.clone()).seal_sync(aad, envelope)
}
/// 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<KeyInfo> {
self.keyring.keys().iter().map(Into::into).collect()
}
/// Returns [`AeadKeyInfo`] for the primary key.
pub fn primary_key(&self) -> KeyInfo {
self.keyring.primary().into()
}
pub fn promote(
&mut self,
key_id: impl Into<u32>,
) -> Result<KeyInfo, crate::error::KeyNotFoundError> {
self.keyring.promote(key_id).map(Into::into)
}
pub fn add(&mut self, algorithm: Algorithm, metadata: Option<Metadata>) -> KeyInfo {
let id = self.keyring.next_id(&SystemRng);
let material = Material::generate(&SystemRng, algorithm);
let key = Key::new(id, Status::Enabled, Origin::Navajo, material, metadata);
self.keyring.add(key).into()
}
pub fn disable(
&mut self,
key_id: impl Into<u32>,
) -> Result<KeyInfo, crate::error::DisableKeyError> {
self.keyring.disable(key_id).map(Into::into)
}
pub fn enable(&mut self, key_id: impl Into<u32>) -> Result<KeyInfo, KeyNotFoundError> {
self.keyring.enable(key_id).map(Into::into)
}
pub fn delete(&mut self, key_id: impl Into<u32>) -> Result<KeyInfo, RemoveKeyError> {
self.keyring.remove(key_id).map(Into::into)
}
/// Sets the metadata for the key with the given ID, returning the previous [`Metadata`] if it exists.
pub fn set_key_metadata(
&mut self,
key_id: impl Into<u32>,
meta: Option<Metadata>,
) -> Result<Option<Metadata>, KeyNotFoundError> {
self.keyring.update_key_metadata(key_id, meta)
}
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 key = Key::new(id, Status::Primary, Origin::Navajo, material, metadata);
let keyring = Keyring::new(key);
Self { keyring }
}
pub fn info(&self) -> KeyringInfo {
KeyringInfo {
keys: self.keys(),
version: self.keyring().version,
kind: crate::primitive::Kind::Aead,
}
}
}
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, P>(
&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, B>(
&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 test_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_decrypt_in_place() {
let rng = crate::rand::SystemRng;
for algorithm in Algorithm::iter() {
let mut size = 0;
while size == 0 {
size = rng.u32().unwrap() as usize % 3000000;
}
let mut data = vec![0u8; size];
rng.fill(&mut data).unwrap();
let plaintext = data.clone();
let aad = Aad(b"additional data");
let aead = Aead::new(algorithm, None);
aead.encrypt_in_place(aad, &mut data).unwrap();
assert_ne!(data, plaintext);
assert!(!data.is_empty());
aead.decrypt_in_place(aad, &mut data).unwrap();
assert_eq!(data, plaintext);
}
}
#[cfg(feature = "std")]
#[test]
fn test_encrypt_writer() {
use std::io::Write;
let rng = crate::rand::SystemRng;
for algorithm in Algorithm::iter() {
let mut writer = vec![];
let mut size: usize = 0;
while size == 0 {
size = rng.u32().unwrap() as usize % 3000000;
}
let mut data = vec![0u8; size];
rng.fill(&mut data).unwrap();
let aad = Aad(rng.u32().unwrap().to_be_bytes());
let aead = Aead::new(algorithm, None);
aead.encrypt_writer(&mut writer, Aad(aad), Segment::FourKilobytes, |w| {
w.write_all(&data)
})
.unwrap();
let decryptor = Decryptor::new(&aead, writer);
let result: Vec<u8> = decryptor.finalize(aad).unwrap().flatten().collect();
assert_eq!(result, data);
}
}
}