libsodium has a method for comparing two byte sequences in constant time.

Is the idea here to simply avoid early-out if a difference in the data is detected?

When I first heard of such a thing I imagined an operating-system sleep operation to round-up the runtime of the algorithm to some threshold, but this sounds very inefficient.


1 Answer 1


A common method for constant-time comparison goes

  • $r←0$
  • for each bit/byte/word $x_i$ and $y_i$ to compare
  • all the $x_i$ match the corresponding $y_i$ if and only if $r$ is now $0$

The point is that the duration is independent of the data compared, thus measuring that duration does not reveal anything about the data.

Other methods are possible, like hashing all the $x_i$, and all the $y_i$ (perhaps with the same random prefix), then comparing the result (preferably, using a similar constant time method). This could be less sensitive to other forms of side-channel attacks.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.