Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 1 | /** |
| 2 | * Constant-time functions |
Gilles Peskine | 49540ac | 2022-10-26 18:02:56 +0200 | [diff] [blame] | 3 | */ |
| 4 | /* |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 5 | * Copyright The Mbed TLS Contributors |
Dave Rodgman | 16799db | 2023-11-02 19:47:20 +0000 | [diff] [blame] | 6 | * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 7 | */ |
| 8 | |
| 9 | #ifndef MBEDTLS_CONSTANT_TIME_H |
| 10 | #define MBEDTLS_CONSTANT_TIME_H |
| 11 | |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 12 | #include <stddef.h> |
| 13 | |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 14 | /** Constant-time buffer comparison without branches. |
| 15 | * |
Gabor Mezei | 642eeb2 | 2021-11-03 16:13:32 +0100 | [diff] [blame] | 16 | * This is equivalent to the standard memcmp function, but is likely to be |
Dave Rodgman | 56e5d68 | 2023-08-01 15:04:11 +0100 | [diff] [blame] | 17 | * compiled to code using bitwise operations rather than a branch, such that |
Dave Rodgman | ad9e5b9 | 2023-07-31 12:33:47 +0100 | [diff] [blame] | 18 | * 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 Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 21 | * |
| 22 | * This function can be used to write constant-time code by replacing branches |
| 23 | * with bit operations using masks. |
| 24 | * |
Dave Rodgman | ad9e5b9 | 2023-07-31 12:33:47 +0100 | [diff] [blame] | 25 | * \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 Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 28 | * |
Dave Rodgman | ad9e5b9 | 2023-07-31 12:33:47 +0100 | [diff] [blame] | 29 | * \return Zero if the contents of the two buffers are the same, |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 30 | * otherwise non-zero. |
| 31 | */ |
Gilles Peskine | 449bd83 | 2023-01-11 14:50:10 +0100 | [diff] [blame] | 32 | int mbedtls_ct_memcmp(const void *a, |
| 33 | const void *b, |
| 34 | size_t n); |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 35 | |
Gabor Mezei | 765862c | 2021-10-19 12:22:25 +0200 | [diff] [blame] | 36 | #endif /* MBEDTLS_CONSTANT_TIME_H */ |