Constant Time Comparison
Timing-safe data comparison.
#include <monocypher.h> int crypto_verify16(const uint8_t a, const uint8_t b); int crypto_verify32(const uint8_t a, const uint8_t b); int crypto_verify64(const uint8_t a, const uint8_t b);
Cryptographic operations often require comparison of secrets or values
derived from secrets. Standard comparison functions like
tend to exit when they find the first difference, leaking information
through timing differences.
As an example, say a message authentication code (MAC) is sent over the network along with a message, but the correct MAC is secret. If the attacker attempts a forgery, one does not want to reveal "your MAC is wrong, and it took 384 microseconds to tell". If the next attempt takes 462 microseconds instead, it tells the attacker they just guessed a few bytes correctly. That way, an attacker can derive the correct MAC, and successfully forge a message. This has lead to practical attacks in the past.
To avoid such catastrophic failure,
crypto_verify64() provide comparison functions
whose timing is independent from the content of their input. They
compare the first 16, 32, or 64 bytes of the two byte arrays
When in doubt, prefer these over
These functions return 0 if the two memory chunks are the same, -1 otherwise.