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
//! Authenticated Encryption with Associated Data Algorithms: AES-GCM, ChaCha20Poly1305

pub use aead::{AeadCore, AeadInPlace, Buffer, Error, KeyInit, KeySizeUser};

#[cfg(feature = "alloc")]
pub use aead::{Aead, Payload};

use aead::{
    consts::{U0, U12, U16, U32},
    generic_array::GenericArray,
};
use ring::aead::{
    Aad, LessSafeKey as Key, Nonce, UnboundKey, AES_128_GCM, AES_256_GCM, CHACHA20_POLY1305,
};

/// Authentication tags
pub type Tag = GenericArray<u8, U16>;

/// AES-GCM with a 128-bit key
pub struct Aes128Gcm(Cipher);

/// AES-GCM with a 256-bit key
pub struct Aes256Gcm(Cipher);

/// ChaCha20Poly1305
pub struct ChaCha20Poly1305(Cipher);

macro_rules! impl_aead {
    ($cipher:ty, $algorithm:expr, $key_size:ty) => {
        impl KeySizeUser for $cipher {
            type KeySize = $key_size;
        }

        impl KeyInit for $cipher {
            fn new(key: &GenericArray<u8, Self::KeySize>) -> Self {
                let key = UnboundKey::new(&$algorithm, key.as_slice()).unwrap();
                Self(Cipher::new(key))
            }
        }

        impl AeadCore for $cipher {
            type NonceSize = U12;
            type TagSize = U16;
            type CiphertextOverhead = U0;
        }

        impl AeadInPlace for $cipher {
            fn encrypt_in_place_detached(
                &self,
                nonce: &GenericArray<u8, Self::NonceSize>,
                associated_data: &[u8],
                buffer: &mut [u8],
            ) -> Result<Tag, Error> {
                self.0
                    .encrypt_in_place_detached(nonce.as_slice(), associated_data, buffer)
            }

            fn decrypt_in_place(
                &self,
                nonce: &GenericArray<u8, Self::NonceSize>,
                associated_data: &[u8],
                buffer: &mut dyn Buffer,
            ) -> Result<(), Error> {
                self.0
                    .decrypt_in_place(nonce.as_slice(), associated_data, buffer)
            }

            fn decrypt_in_place_detached(
                &self,
                _nonce: &GenericArray<u8, Self::NonceSize>,
                _associated_data: &[u8],
                _buffer: &mut [u8],
                _tag: &Tag,
            ) -> Result<(), Error> {
                unimplemented!(); // ring does not allow us to implement this API
            }
        }
    };
}

impl_aead!(Aes128Gcm, AES_128_GCM, U16);
impl_aead!(Aes256Gcm, AES_256_GCM, U32);
impl_aead!(ChaCha20Poly1305, CHACHA20_POLY1305, U32);

/// Generic AEAD cipher support
pub(crate) struct Cipher(Key);

impl Cipher {
    /// Instantiate a particular AEAD algorithm
    pub fn new(key: UnboundKey) -> Self {
        Cipher(Key::new(key))
    }

    /// Encrypt the ciphertext in place, returning a tag
    fn encrypt_in_place_detached(
        &self,
        nonce: &[u8],
        associated_data: &[u8],
        buffer: &mut [u8],
    ) -> Result<Tag, Error> {
        self.0
            .seal_in_place_separate_tag(
                Nonce::try_assume_unique_for_key(nonce).map_err(|_| Error)?,
                Aad::from(associated_data),
                buffer,
            )
            .map(|tag| Tag::clone_from_slice(tag.as_ref()))
            .map_err(|_| Error)
    }

    fn decrypt_in_place(
        &self,
        nonce: &[u8],
        associated_data: &[u8],
        buffer: &mut dyn Buffer,
    ) -> Result<(), Error> {
        let pt_len = self
            .0
            .open_in_place(
                Nonce::try_assume_unique_for_key(nonce).map_err(|_| Error)?,
                Aad::from(associated_data),
                buffer.as_mut(),
            )
            .map_err(|_| Error)?
            .len();

        buffer.truncate(pt_len);
        Ok(())
    }
}