Skip to content

Commit 217851e

Browse files
committed
chacha20poly1305: Switch to one-pass encryption and decryption
1 parent e4b2d2f commit 217851e

File tree

1 file changed

+14
-8
lines changed

1 file changed

+14
-8
lines changed

chacha20poly1305/src/cipher.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,10 +58,10 @@ where
5858

5959
self.mac.update_padded(associated_data);
6060

61-
// TODO(tarcieri): interleave encryption with Poly1305
62-
// See: <https://github.com/RustCrypto/AEADs/issues/74>
63-
self.cipher.apply_keystream(buffer);
64-
self.mac.update_padded(buffer);
61+
for block in buffer.chunks_mut(BLOCK_SIZE) {
62+
self.cipher.apply_keystream(block);
63+
self.mac.update_padded(block);
64+
}
6565

6666
self.authenticate_lengths(associated_data, buffer)?;
6767
Ok(self.mac.finalize())
@@ -80,16 +80,22 @@ where
8080
}
8181

8282
self.mac.update_padded(associated_data);
83-
self.mac.update_padded(buffer);
83+
84+
for block in buffer.chunks_mut(BLOCK_SIZE) {
85+
self.mac.update_padded(block);
86+
self.cipher.apply_keystream(block);
87+
}
88+
8489
self.authenticate_lengths(associated_data, buffer)?;
8590

8691
// This performs a constant-time comparison using the `subtle` crate
8792
if self.mac.verify(tag).is_ok() {
88-
// TODO(tarcieri): interleave decryption with Poly1305
89-
// See: <https://github.com/RustCrypto/AEADs/issues/74>
90-
self.cipher.apply_keystream(buffer);
9193
Ok(())
9294
} else {
95+
// On MAC verify failure, re-encrypt the plaintext buffer to prevent
96+
// accidental exposure.
97+
self.cipher.seek(BLOCK_SIZE as u64);
98+
self.cipher.apply_keystream(buffer);
9399
Err(Error)
94100
}
95101
}

0 commit comments

Comments
 (0)