Answer#
== on byte slices returns as soon as it finds a difference. In principle, an attacker who can measure response times precisely enough could learn a token one byte at a time. This is hard to exploit over a network and easy to avoid, so use a comparison whose running time does not depend on where the difference is.
[dependencies]
subtle = "2.6"
hmac = "0.12"
sha2 = "0.10"use hmac::{Hmac, Mac};
use sha2::Sha256;
use subtle::ConstantTimeEq;
fn main() {
// 1. Comparing two secrets of the same length without stopping at the first difference.
let stored = b"0123456789abcdef";
let supplied = b"0123456789abcdeX";
println!("equal: {}", bool::from(stored.ct_eq(supplied)));
println!("equal: {}", bool::from(stored.ct_eq(stored)));
// 2. Checking a MAC: `verify_slice` compares in constant time for you.
let key = b"a demo key, not for real use";
let mut mac = Hmac::<Sha256>::new_from_slice(key).unwrap();
mac.update(b"user=42");
let tag = mac.finalize().into_bytes();
let mut check = Hmac::<Sha256>::new_from_slice(key).unwrap();
check.update(b"user=42");
println!("tag ok: {}", check.verify_slice(&tag).is_ok());
let mut forged = Hmac::<Sha256>::new_from_slice(key).unwrap();
forged.update(b"user=1");
println!("other message ok: {}", forged.verify_slice(&tag).is_ok());
}equal: false
equal: true
tag ok: true
other message ok: falsect_eq returns a Choice, not a bool; convert with bool::from at the very end. For a MAC, verify_slice already compares in constant time. Slices of different length compare as not equal straight away: the length is not treated as secret.
How to do it#
- Compare equal-length secrets (tokens, MAC tags, API keys) with
ct_eq. - For HMAC tags, call
verify_slice; do not compute the tag and compare with==. - For passwords, use the verify function of your hashing crate.
- Keep the
Choiceas aChoiceas long as you can, and convert once.
Common mistakes#
- Branching on secret data before the comparison (an early
returnat the first different byte in your own loop). - Believing constant-time comparison fixes weak tokens. A guessable token is guessable at any speed.
Related questions#
Does this matter when I look a session up by its hash?#
A database lookup by a hash of the token reveals nothing useful about the token itself, because an attacker cannot choose inputs that share a prefix with the stored value. That is one reason to store only hashes of session IDs.
When is a plain comparison fine?#
For values that are not secret: public IDs, version strings, file names. Use constant-time comparison when an attacker could learn something from the result of comparing a secret.
Sources#
subtledocumentation: https://docs.rs/subtle/2.6.1/subtle/trait.ConstantTimeEq.htmlhmacdocumentation,Mac::verify_slice: https://docs.rs/hmac/0.12.1/hmac/trait.Mac.html- OWASP Cryptographic Storage Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Cryptographic_Storage_Cheat_Sheet.html