blob: d31bff677e9dd444ce01dec8d526b6bae94592fb [file] [log] [blame]
Gabor Mezei765862c2021-10-19 12:22:25 +02001/**
2 * Constant-time functions
Gilles Peskine49540ac2022-10-26 18:02:56 +02003 */
4/*
Gabor Mezei765862c2021-10-19 12:22:25 +02005 * Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +00006 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gabor Mezei765862c2021-10-19 12:22:25 +02007 */
8
9#ifndef MBEDTLS_CONSTANT_TIME_H
10#define MBEDTLS_CONSTANT_TIME_H
11
Gabor Mezei765862c2021-10-19 12:22:25 +020012#include <stddef.h>
13
Gabor Mezei765862c2021-10-19 12:22:25 +020014/** Constant-time buffer comparison without branches.
15 *
Gabor Mezei642eeb22021-11-03 16:13:32 +010016 * This is equivalent to the standard memcmp function, but is likely to be
Dave Rodgman56e5d682023-08-01 15:04:11 +010017 * compiled to code using bitwise operations rather than a branch, such that
Dave Rodgmanad9e5b92023-07-31 12:33:47 +010018 * the time taken is constant w.r.t. the data pointed to by \p a and \p b,
19 * and w.r.t. whether \p a and \p b are equal or not. It is not constant-time
20 * w.r.t. \p n .
Gabor Mezei765862c2021-10-19 12:22:25 +020021 *
22 * This function can be used to write constant-time code by replacing branches
23 * with bit operations using masks.
24 *
Dave Rodgmanad9e5b92023-07-31 12:33:47 +010025 * \param a Pointer to the first buffer, containing at least \p n bytes. May not be NULL.
26 * \param b Pointer to the second buffer, containing at least \p n bytes. May not be NULL.
27 * \param n The number of bytes to compare.
Gabor Mezei765862c2021-10-19 12:22:25 +020028 *
Dave Rodgmanad9e5b92023-07-31 12:33:47 +010029 * \return Zero if the contents of the two buffers are the same,
Gabor Mezei765862c2021-10-19 12:22:25 +020030 * otherwise non-zero.
31 */
Gilles Peskine449bd832023-01-11 14:50:10 +010032int mbedtls_ct_memcmp(const void *a,
33 const void *b,
34 size_t n);
Gabor Mezei765862c2021-10-19 12:22:25 +020035
Gabor Mezei765862c2021-10-19 12:22:25 +020036#endif /* MBEDTLS_CONSTANT_TIME_H */