Skip to content

Commit 10acc1b

Browse files
authored
ssh-cipher: improve Poly1305 tests (#373)
Try all combinations of AAD and plaintext lengths up to the Poly1305 block size
1 parent dedcbcf commit 10acc1b

1 file changed

Lines changed: 27 additions & 2 deletions

File tree

ssh-cipher/src/chacha20poly1305.rs

Lines changed: 27 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,7 @@ impl Cipher {
137137
fn compute_mac(mut mac: Poly1305, aad: &[u8], buffer: &[u8]) -> Result<Tag> {
138138
match aad.len() {
139139
0 => Ok(mac.compute_unpadded(buffer)),
140-
1..poly1305::BLOCK_SIZE => {
140+
1..=poly1305::BLOCK_SIZE => {
141141
let mut block = poly1305::Block::default();
142142
block[..aad.len()].copy_from_slice(aad);
143143

@@ -159,7 +159,7 @@ fn compute_mac(mut mac: Poly1305, aad: &[u8], buffer: &[u8]) -> Result<Tag> {
159159

160160
#[cfg(test)]
161161
mod tests {
162-
use super::{AeadInOut, ChaCha20Poly1305, KeyInit};
162+
use super::{AeadInOut, ChaCha20Poly1305, KeyInit, Poly1305, compute_mac};
163163
use hex_literal::hex;
164164

165165
#[test]
@@ -191,4 +191,29 @@ mod tests {
191191

192192
assert_eq!(buffer, plaintext);
193193
}
194+
195+
#[test]
196+
fn mac_computation_with_aad() {
197+
const KEY: &[u8; poly1305::KEY_SIZE] = b"11112222333344445555666677778888";
198+
const AAD: &[u8; poly1305::BLOCK_SIZE] = b"0123456789ABCDEF";
199+
const PT: &[u8; poly1305::BLOCK_SIZE] = b"abcdefghijklmnop";
200+
201+
for aad_len in 0..=poly1305::BLOCK_SIZE {
202+
for pt_len in 0..=poly1305::BLOCK_SIZE {
203+
let mut buffer = [0; poly1305::BLOCK_SIZE * 2];
204+
let aad = &AAD[..aad_len];
205+
let pt = &PT[..pt_len];
206+
207+
let eob = aad_len + pt_len;
208+
buffer[..aad_len].copy_from_slice(aad);
209+
buffer[aad_len..eob].copy_from_slice(pt);
210+
211+
let poly = Poly1305::new(KEY.as_ref());
212+
let expected_mac = poly.clone().compute_unpadded(&buffer[..eob]);
213+
let actual_mac = compute_mac(poly, aad, pt).unwrap();
214+
215+
assert_eq!(expected_mac, actual_mac);
216+
}
217+
}
218+
}
194219
}

0 commit comments

Comments
 (0)