From bf603424e9d82a4760c8fd12a7eb1e3b0a6a5d5a Mon Sep 17 00:00:00 2001 From: Daniel Schadt Date: Tue, 8 Apr 2025 22:20:56 +0200 Subject: use constant_time_eq in decryption function --- Cargo.lock | 7 +++++++ Cargo.toml | 1 + src/lib.rs | 6 ++++-- 3 files changed, 12 insertions(+), 2 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 50d12c4..068b46e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -47,6 +47,12 @@ dependencies = [ "inout", ] +[[package]] +name = "constant_time_eq" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d52eff69cd5e647efe296129160853a42795992097e8af39800e1060caeea9b" + [[package]] name = "cpufeatures" version = "0.2.17" @@ -132,5 +138,6 @@ version = "0.1.0" dependencies = [ "aes", "blake2", + "constant_time_eq", "hex", ] diff --git a/Cargo.toml b/Cargo.toml index aa191ad..894e269 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -9,6 +9,7 @@ readme = "README.md" [dependencies] aes = { version = "0.8.4", features = ["hazmat"] } blake2 = "0.10.6" +constant_time_eq = "0.4.2" [dev-dependencies] hex = "0.4.3" diff --git a/src/lib.rs b/src/lib.rs index cc6cd9c..46070fc 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -84,6 +84,8 @@ //! ``` use std::iter; +use constant_time_eq::constant_time_eq; + mod block; #[cfg(test)] mod testvectors; @@ -234,7 +236,7 @@ fn decrypt(key: &Key, nonce: &[u8], ad: &[&[u8]], tau: u32, ciphertext: &[u8]) - tweaks.extend(ad); if ciphertext.len() == tau as usize { - if ciphertext == aez_prf(key, &tweaks, tau) { + if constant_time_eq(&ciphertext, &aez_prf(key, &tweaks, tau)) { return Some(Vec::new()); } else { return None; @@ -244,7 +246,7 @@ fn decrypt(key: &Key, nonce: &[u8], ad: &[&[u8]], tau: u32, ciphertext: &[u8]) - let x = decipher(key, &tweaks, ciphertext); let (m, auth) = x.split_at(ciphertext.len() - tau as usize); assert!(auth.len() == tau as usize); - if auth.iter().all(|x| *x == 0) { + if constant_time_eq(&auth, &vec![0; tau as usize]) { Some(Vec::from(m)) } else { None -- cgit v1.2.3