ssh_cipher/
chacha20poly1305.rs1pub use chacha20::ChaCha20Legacy as ChaCha20;
4
5use crate::Tag;
6use aead::{
7 AeadCore, AeadInOut, Error, KeyInit, KeySizeUser, Result, TagPosition,
8 array::typenum::{U8, U16, U32},
9 inout::InOutBuf,
10};
11use cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
12use core::fmt::{self, Debug};
13use ctutils::CtEq;
14use poly1305::{Poly1305, universal_hash::UniversalHash};
15
16#[cfg(feature = "zeroize")]
17use zeroize::{Zeroize, ZeroizeOnDrop};
18
19pub type ChaChaKey = chacha20::Key;
21
22pub type ChaChaNonce = chacha20::LegacyNonce;
24
25#[derive(Clone)]
106pub struct ChaCha20Poly1305 {
107 key: ChaChaKey,
108}
109
110impl KeySizeUser for ChaCha20Poly1305 {
111 type KeySize = U32;
112}
113
114impl KeyInit for ChaCha20Poly1305 {
115 #[inline]
116 fn new(key: &ChaChaKey) -> Self {
117 Self { key: *key }
118 }
119}
120
121impl AeadCore for ChaCha20Poly1305 {
122 type NonceSize = U8;
123 type TagSize = U16;
124 const TAG_POSITION: TagPosition = TagPosition::Postfix;
125}
126
127impl AeadInOut for ChaCha20Poly1305 {
128 fn encrypt_inout_detached(
129 &self,
130 nonce: &ChaChaNonce,
131 associated_data: &[u8],
132 buffer: InOutBuf<'_, '_, u8>,
133 ) -> Result<Tag> {
134 Cipher::new(&self.key, *nonce).encrypt(associated_data, buffer)
135 }
136
137 fn decrypt_inout_detached(
138 &self,
139 nonce: &ChaChaNonce,
140 associated_data: &[u8],
141 buffer: InOutBuf<'_, '_, u8>,
142 tag: &Tag,
143 ) -> Result<()> {
144 Cipher::new(&self.key, *nonce).decrypt(associated_data, buffer, tag)
145 }
146}
147
148impl Debug for ChaCha20Poly1305 {
149 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150 f.debug_struct("ChaCha20Poly1305").finish_non_exhaustive()
151 }
152}
153
154impl Drop for ChaCha20Poly1305 {
155 fn drop(&mut self) {
156 #[cfg(feature = "zeroize")]
157 self.key.zeroize();
158 }
159}
160
161#[cfg(feature = "zeroize")]
162impl ZeroizeOnDrop for ChaCha20Poly1305 {}
163
164struct Cipher {
166 cipher: ChaCha20,
167 mac: Poly1305,
168}
169
170impl Cipher {
171 fn new(key: &ChaChaKey, nonce: ChaChaNonce) -> Self {
173 let mut cipher = ChaCha20::new(key, &nonce);
174 let mut poly1305_key = poly1305::Key::default();
175 cipher.apply_keystream(&mut poly1305_key);
176
177 let mac = Poly1305::new(&poly1305_key);
178
179 cipher.seek(64);
181
182 Self { cipher, mac }
183 }
184
185 #[inline]
187 fn encrypt(mut self, aad: &[u8], mut buffer: InOutBuf<'_, '_, u8>) -> Result<Tag> {
188 self.cipher.apply_keystream_inout(buffer.reborrow());
189 compute_mac(self.mac, aad, buffer.get_out())
190 }
191
192 #[inline]
195 fn decrypt(mut self, aad: &[u8], buffer: InOutBuf<'_, '_, u8>, tag: &Tag) -> Result<()> {
196 let expected_tag = compute_mac(self.mac, aad, buffer.get_in())?;
197
198 if expected_tag.ct_eq(tag).into() {
199 self.cipher.apply_keystream_inout(buffer);
200 Ok(())
201 } else {
202 Err(Error)
203 }
204 }
205}
206
207fn compute_mac(mut mac: Poly1305, aad: &[u8], buffer: &[u8]) -> Result<Tag> {
209 if aad.len() > poly1305::BLOCK_SIZE {
212 return Err(Error);
213 }
214
215 let mut block = poly1305::Block::default();
217 block[..aad.len()].copy_from_slice(aad);
218
219 let block_remaining = poly1305::BLOCK_SIZE.checked_sub(aad.len()).ok_or(Error)?;
220 let remaining = if buffer.len() <= block_remaining {
221 let msg_len = aad.len().checked_add(buffer.len()).ok_or(Error)?;
223 block[aad.len()..msg_len].copy_from_slice(buffer);
224 &block[..msg_len]
225 } else {
226 let (head, tail) = buffer.split_at(block_remaining);
228 block[aad.len()..].copy_from_slice(head);
229 mac.update(&[block]);
230 tail
231 };
232
233 Ok(mac.compute_unpadded(remaining))
235}
236
237#[cfg(test)]
238mod tests {
239 use super::{AeadInOut, ChaCha20Poly1305, KeyInit, Poly1305, compute_mac};
240 use hex_literal::hex;
241
242 #[test]
243 fn test_vector() {
244 const KEY: [u8; 32] =
245 hex!("379a8ca9e7e705763633213511e8d92eb148a46f1dd0045ec8164e5d23e456eb");
246 const NONCE: [u8; 8] = hex!("0000000000000003");
247 const AAD: [u8; 4] = hex!("5709db2d");
248 const PT: [u8; 24] = hex!("06050000000c7373682d7573657261757468de5949ab061f");
249 const CT: [u8; 24] = hex!("6dcfb03be8a55e7f0220465672edd921489ea0171198e8a7");
250 const TAG: [u8; 16] = hex!("3e82fe0a2db7128d58ef8d9047963ca3");
251
252 let cipher = ChaCha20Poly1305::new(&KEY.into());
253 let mut buffer = PT;
254 let actual_tag = cipher
255 .encrypt_inout_detached(&NONCE.into(), &AAD, buffer.as_mut_slice().into())
256 .unwrap();
257
258 assert_eq!(buffer, CT);
259 assert_eq!(actual_tag, TAG);
260
261 cipher
262 .decrypt_inout_detached(
263 &NONCE.into(),
264 &AAD,
265 buffer.as_mut_slice().into(),
266 &actual_tag,
267 )
268 .unwrap();
269
270 assert_eq!(buffer, PT);
271 }
272
273 #[test]
274 fn mac_computation_with_aad() {
275 const KEY: &[u8; poly1305::KEY_SIZE] = b"11112222333344445555666677778888";
276 const AAD: &[u8; poly1305::BLOCK_SIZE] = b"0123456789ABCDEF";
277 const PT: &[u8; poly1305::BLOCK_SIZE] = b"abcdefghijklmnop";
278
279 for aad_len in 0..=poly1305::BLOCK_SIZE {
280 for pt_len in 0..=poly1305::BLOCK_SIZE {
281 let mut buffer = [0; poly1305::BLOCK_SIZE * 2];
282 let aad = &AAD[..aad_len];
283 let pt = &PT[..pt_len];
284
285 let eob = aad_len + pt_len;
286 buffer[..aad_len].copy_from_slice(aad);
287 buffer[aad_len..eob].copy_from_slice(pt);
288
289 let poly = Poly1305::new(KEY.into());
290 let expected_mac = poly.clone().compute_unpadded(&buffer[..eob]);
291 let actual_mac = compute_mac(poly, aad, pt).unwrap();
292
293 assert_eq!(expected_mac, actual_mac);
294 }
295 }
296 }
297}