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
//! [`Aes256CtrPoly1305Aes`] is an [Authenticated Encryption with Associated Data
//! (AEAD)][2] cipher amenable to fast, constant-time implementations in software,
//! based on the [AES256-CTR][3] stream cipher and the [Poly1305-AES MAC] [4]
//! which uses the [Poly1305][5] universal hash function in combination with the
//! [AES-128][6] block cipher.
//!
//! A lot code is copied from the [chacha20poly1305 crate][7]
//!
//! This crate contains pure Rust implementations of [`Aes256CtrPoly1305Aes`]
//! (with optional AVX2 acceleration) as well as the following variants thereof:
//!
//! All implementations contained in the crate are designed to execute in
//! constant time, either by relying on hardware intrinsics (i.e. AVX2 on
//! x86/x86_64), or using a portable implementation which is only constant time
//! on processors which implement constant-time multiplication.
//!
//! It is not suitable for use on processors with a variable-time multiplication
//! operation (e.g. short circuit on multiply-by-zero / multiply-by-one, such as
//! certain 32-bit PowerPC CPUs and some non-ARM microcontrollers).
//!
//! # Usage
//!
//! ```
//! # #[cfg(feature = "alloc")]
//! # {
//! use aes256ctr_poly1305aes::{Aes256CtrPoly1305Aes, Key, Nonce};
//! use aes256ctr_poly1305aes::aead::Aead;
//!
//! // 64 bytes key
//! let key = Key::from_slice(b"This is an example of a very secret key. Keep it always secret!!");
//! let cipher = Aes256CtrPoly1305Aes::new(key);
//!
//! let nonce = Nonce::from_slice(b"my unique nonce!"); // 16-bytes; unique per message
//!
//! let ciphertext = cipher.encrypt(nonce, b"plaintext message".as_ref())
//!     .expect("encryption failure!");  // NOTE: handle this error to avoid panics!
//! let plaintext = cipher.decrypt(nonce, ciphertext.as_ref())
//!     .expect("decryption failure!");  // NOTE: handle this error to avoid panics!
//!
//! assert_eq!(&plaintext, b"plaintext message");
//! # }
//! ```
//!
//! ## In-place Usage (eliminates `alloc` requirement)
//!
//! This crate has an optional `alloc` feature which can be disabled in e.g.
//! microcontroller environments that don't have a heap.
//!
//! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`]
//! methods accept any type that impls the [`aead::Buffer`] trait which
//! contains the plaintext for encryption or ciphertext for decryption.
//!
//! Note that if you enable the `heapless` feature of this crate,
//! you will receive an impl of [`aead::Buffer`] for `heapless::Vec`
//! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]),
//! which can then be passed as the `buffer` parameter to the in-place encrypt
//! and decrypt methods:
//!
//! ```
//! # #[cfg(feature = "heapless")]
//! # {
//! use aes256ctr_poly1305aes::{Aes256CtrPoly1305Aes, Key, Nonce};
//! use aes256ctr_poly1305aes::aead::{AeadInPlace, NewAead};
//! use aes256ctr_poly1305aes::aead::heapless::Vec;
//!
//! // 64 bytes key
//! let key = Key::from_slice(b"This is an example of a very secret key. Keep it always secret!!");
//! let cipher = Aes256CtrPoly1305Aes::new(key);
//!
//! let nonce = Nonce::from_slice(b"my unique nonce!"); // 16-bytes; unique per message
//!
//! let mut buffer: Vec<u8, 128> = Vec::new();
//! buffer.extend_from_slice(b"plaintext message");
//!
//! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext
//! cipher.encrypt_in_place(nonce, b"", &mut buffer).expect("encryption failure!");
//!
//! // `buffer` now contains the message ciphertext
//! assert_ne!(&buffer, b"plaintext message");
//!
//! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext
//! cipher.decrypt_in_place(nonce, b"", &mut buffer).expect("decryption failure!");
//! assert_eq!(&buffer, b"plaintext message");
//! # }
//! ```
//!
//! [1]: https://tools.ietf.org/html/rfc8439
//! [2]: https://en.wikipedia.org/wiki/Authenticated_encryption
//! [3]: https://docs.rs/aes/latest/aes/struct.Aes256Ctr.html
//! [4]: https://cr.yp.to/mac/poly1305-20050329.pdf
//! [5]: https://github.com/RustCrypto/universal-hashes/tree/master/poly1305
//! [6]: https://docs.rs/aes/latest/aes/struct.Aes128.html
//! [7]: https://crates.io/crates/chacha20poly1305

#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
    html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
    html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
)]
#![warn(missing_docs, rust_2018_idioms)]

mod cipher;

pub use aead;

use self::cipher::Cipher;
use aead::{
    consts::{U0, U16, U32, U64},
    generic_array::GenericArray,
    AeadCore, AeadInPlace, Error, KeyInit,
};
use ctr::Ctr64BE;
use zeroize::Zeroize;

use ::cipher::{BlockEncrypt, KeyIvInit};
use aes::{Aes128, Aes256};
use poly1305::Poly1305;

type Aes256Ctr = Ctr64BE<Aes256>;

/// Key type (512-bits/64-bytes).
///
/// Implemented as an alias for [`GenericArray`].
pub type Key = GenericArray<u8, U64>;

/// Nonce type (128-bits/16-bytes).
///
/// Implemented as an alias for [`GenericArray`].
pub type Nonce = GenericArray<u8, U16>;

/// Poly1305 tag.
///
/// Implemented as an alias for [`GenericArray`].
pub type Tag = GenericArray<u8, U16>;

/// Authenticated Encryption with Additional Data (AEAD) using AES256-CTR and Poly1305-AES.
///
/// See the [toplevel documentation](index.html) for a usage example.
#[derive(Clone, Debug)]
pub struct Aes256CtrPoly1305Aes {
    /// Secret key for Aes256Ctr
    aes256ctr_key: GenericArray<u8, U32>,

    /// Secret key for Aes128r
    aes128_key: GenericArray<u8, U16>,

    /// Secret value r for Poly1305
    poly1305_r: GenericArray<u8, U16>,
}

impl Aes256CtrPoly1305Aes {
    fn cipher_from_nonce(&self, nonce: &aead::Nonce<Self>) -> Cipher<Aes256Ctr> {
        // Derive Poly1305 key from r and AES_k(nonce)
        let mut mac_key = poly1305::Key::default();
        mac_key[0..16].copy_from_slice(&self.poly1305_r);

        let mut block = *nonce;
        Aes128::new(&self.aes128_key).encrypt_block(&mut block);
        mac_key[16..32].copy_from_slice(&block);
        block.zeroize();

        let cipher = Cipher::new(
            <Aes256Ctr as KeyIvInit>::new(&self.aes256ctr_key, nonce),
            Poly1305::new(&mac_key),
        );
        mac_key.zeroize();
        cipher
    }

    /// New AEAD using AES256-CTR and Poly1305-AES from the given 64-byte key.
    /// The first 32 bytes are used as key for AES256-CTR.
    /// The following 16 bytes are used as key for the AES128 used in Poly1305-AES.
    /// The last 16 bytes are used as r in Poly1305-AES.
    pub fn new(key: &Key) -> Self {
        Self {
            aes256ctr_key: GenericArray::clone_from_slice(&key[0..32]),
            aes128_key: GenericArray::clone_from_slice(&key[32..48]),
            poly1305_r: GenericArray::clone_from_slice(&key[48..64]),
        }
    }
}

impl AeadCore for Aes256CtrPoly1305Aes {
    type NonceSize = U16;
    type TagSize = U16;
    type CiphertextOverhead = U0;
}

impl AeadInPlace for Aes256CtrPoly1305Aes {
    fn encrypt_in_place_detached(
        &self,
        nonce: &aead::Nonce<Self>,
        associated_data: &[u8],
        buffer: &mut [u8],
    ) -> Result<Tag, Error> {
        self.cipher_from_nonce(nonce)
            .encrypt_in_place_detached(associated_data, buffer)
    }

    fn decrypt_in_place_detached(
        &self,
        nonce: &aead::Nonce<Self>,
        associated_data: &[u8],
        buffer: &mut [u8],
        tag: &Tag,
    ) -> Result<(), Error> {
        self.cipher_from_nonce(nonce)
            .decrypt_in_place_detached(associated_data, buffer, tag)
    }
}

impl Drop for Aes256CtrPoly1305Aes {
    fn drop(&mut self) {
        self.aes256ctr_key.as_mut_slice().zeroize();
        self.aes128_key.as_mut_slice().zeroize();
        self.poly1305_r.as_mut_slice().zeroize();
    }
}