blob: 80916946152467931a6c93b15cc1b2ce192def8f [file] [log] [blame]
Janos Follath3ca07752022-08-09 11:45:47 +01001/*
Janos Follatha95f2042022-08-19 12:09:17 +01002 * Core bignum functions
Janos Follath3ca07752022-08-09 11:45:47 +01003 *
4 * Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +00005 * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Janos Follath3ca07752022-08-09 11:45:47 +01006 */
7
8#include "common.h"
9
10#if defined(MBEDTLS_BIGNUM_C)
11
12#include <string.h>
13
14#include "mbedtls/error.h"
15#include "mbedtls/platform_util.h"
Gabor Mezeie1d31c42022-09-12 16:25:24 +020016#include "constant_time_internal.h"
Janos Follath3ca07752022-08-09 11:45:47 +010017
Janos Follath3ca07752022-08-09 11:45:47 +010018#include "mbedtls/platform.h"
Janos Follath3ca07752022-08-09 11:45:47 +010019
20#include "bignum_core.h"
Manuel Pégourié-Gonnard7fba4662025-07-17 09:17:12 +020021#include "bignum_core_invasive.h"
Tom Cosgrove958fd3d2022-08-24 11:08:51 +010022#include "bn_mul.h"
23#include "constant_time_internal.h"
Janos Follath3ca07752022-08-09 11:45:47 +010024
Dave Rodgman914347b2023-04-27 14:20:30 +010025size_t mbedtls_mpi_core_clz(mbedtls_mpi_uint a)
26{
27#if defined(__has_builtin)
Agathiyan Bragadeeshe55a1e12023-07-17 15:00:19 +010028#if (MBEDTLS_MPI_UINT_MAX == UINT_MAX) && __has_builtin(__builtin_clz)
29 #define core_clz __builtin_clz
30#elif (MBEDTLS_MPI_UINT_MAX == ULONG_MAX) && __has_builtin(__builtin_clzl)
31 #define core_clz __builtin_clzl
32#elif (MBEDTLS_MPI_UINT_MAX == ULLONG_MAX) && __has_builtin(__builtin_clzll)
33 #define core_clz __builtin_clzll
Dave Rodgman914347b2023-04-27 14:20:30 +010034#endif
35#endif
Agathiyan Bragadeeshe55a1e12023-07-17 15:00:19 +010036#if defined(core_clz)
37 return (size_t) core_clz(a);
Agathiyan Bragadeesh271a9532023-07-12 11:15:17 +010038#else
Dave Rodgman914347b2023-04-27 14:20:30 +010039 size_t j;
40 mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);
41
42 for (j = 0; j < biL; j++) {
43 if (a & mask) {
44 break;
45 }
46
47 mask >>= 1;
48 }
49
50 return j;
Agathiyan Bragadeesh271a9532023-07-12 11:15:17 +010051#endif
Dave Rodgman914347b2023-04-27 14:20:30 +010052}
53
Gilles Peskine449bd832023-01-11 14:50:10 +010054size_t mbedtls_mpi_core_bitlen(const mbedtls_mpi_uint *A, size_t A_limbs)
Janos Follath3ca07752022-08-09 11:45:47 +010055{
Dave Rodgman880a6b32023-04-20 09:50:31 +010056 int i;
57 size_t j;
Janos Follath3ca07752022-08-09 11:45:47 +010058
Dave Rodgman2e863ec2023-04-25 17:34:59 +010059 for (i = ((int) A_limbs) - 1; i >= 0; i--) {
60 if (A[i] != 0) {
61 j = biL - mbedtls_mpi_core_clz(A[i]);
62 return (i * biL) + j;
Gilles Peskine449bd832023-01-11 14:50:10 +010063 }
64 }
Janos Follath3ca07752022-08-09 11:45:47 +010065
Dave Rodgman880a6b32023-04-20 09:50:31 +010066 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +010067}
68
Gilles Peskine449bd832023-01-11 14:50:10 +010069static mbedtls_mpi_uint mpi_bigendian_to_host(mbedtls_mpi_uint a)
Janos Follath3ca07752022-08-09 11:45:47 +010070{
Gilles Peskine449bd832023-01-11 14:50:10 +010071 if (MBEDTLS_IS_BIG_ENDIAN) {
Dave Rodgman6d23ff62022-11-28 14:38:53 +000072 /* Nothing to do on bigendian systems. */
Gilles Peskine449bd832023-01-11 14:50:10 +010073 return a;
74 } else {
Dave Rodgman7e1e7be2023-09-05 18:12:33 +010075#if defined(MBEDTLS_HAVE_INT32)
Dave Rodgmanb7b8c092023-09-05 20:35:19 +010076 return (mbedtls_mpi_uint) MBEDTLS_BSWAP32(a);
Dave Rodgman7e1e7be2023-09-05 18:12:33 +010077#elif defined(MBEDTLS_HAVE_INT64)
Dave Rodgmanb7b8c092023-09-05 20:35:19 +010078 return (mbedtls_mpi_uint) MBEDTLS_BSWAP64(a);
Dave Rodgman7e1e7be2023-09-05 18:12:33 +010079#endif
Dave Rodgman6d23ff62022-11-28 14:38:53 +000080 }
Janos Follath3ca07752022-08-09 11:45:47 +010081}
82
Gilles Peskine449bd832023-01-11 14:50:10 +010083void mbedtls_mpi_core_bigendian_to_host(mbedtls_mpi_uint *A,
84 size_t A_limbs)
Janos Follath3ca07752022-08-09 11:45:47 +010085{
86 mbedtls_mpi_uint *cur_limb_left;
87 mbedtls_mpi_uint *cur_limb_right;
Gilles Peskine449bd832023-01-11 14:50:10 +010088 if (A_limbs == 0) {
Janos Follath3ca07752022-08-09 11:45:47 +010089 return;
Gilles Peskine449bd832023-01-11 14:50:10 +010090 }
Janos Follath3ca07752022-08-09 11:45:47 +010091
92 /*
93 * Traverse limbs and
94 * - adapt byte-order in each limb
95 * - swap the limbs themselves.
96 * For that, simultaneously traverse the limbs from left to right
97 * and from right to left, as long as the left index is not bigger
98 * than the right index (it's not a problem if limbs is odd and the
99 * indices coincide in the last iteration).
100 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100101 for (cur_limb_left = A, cur_limb_right = A + (A_limbs - 1);
Janos Follath3ca07752022-08-09 11:45:47 +0100102 cur_limb_left <= cur_limb_right;
Gilles Peskine449bd832023-01-11 14:50:10 +0100103 cur_limb_left++, cur_limb_right--) {
Janos Follath3ca07752022-08-09 11:45:47 +0100104 mbedtls_mpi_uint tmp;
105 /* Note that if cur_limb_left == cur_limb_right,
106 * this code effectively swaps the bytes only once. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100107 tmp = mpi_bigendian_to_host(*cur_limb_left);
108 *cur_limb_left = mpi_bigendian_to_host(*cur_limb_right);
Janos Follath3ca07752022-08-09 11:45:47 +0100109 *cur_limb_right = tmp;
110 }
111}
112
Gilles Peskine6f949ea2022-09-20 18:38:35 +0200113/* Whether min <= A, in constant time.
114 * A_limbs must be at least 1. */
Dave Rodgmanfd7fab42023-05-17 14:00:39 +0100115mbedtls_ct_condition_t mbedtls_mpi_core_uint_le_mpi(mbedtls_mpi_uint min,
116 const mbedtls_mpi_uint *A,
117 size_t A_limbs)
Gilles Peskine6f949ea2022-09-20 18:38:35 +0200118{
119 /* min <= least significant limb? */
Dave Rodgmanb7825ce2023-08-10 11:58:18 +0100120 mbedtls_ct_condition_t min_le_lsl = mbedtls_ct_uint_ge(A[0], min);
Gilles Peskine6f949ea2022-09-20 18:38:35 +0200121
Gilles Peskine6b7ce962022-12-15 15:04:33 +0100122 /* limbs other than the least significant one are all zero? */
Dave Rodgmanfd7fab42023-05-17 14:00:39 +0100123 mbedtls_ct_condition_t msll_mask = MBEDTLS_CT_FALSE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100124 for (size_t i = 1; i < A_limbs; i++) {
Dave Rodgmanfd7fab42023-05-17 14:00:39 +0100125 msll_mask = mbedtls_ct_bool_or(msll_mask, mbedtls_ct_bool(A[i]));
Gilles Peskine449bd832023-01-11 14:50:10 +0100126 }
Gilles Peskine6f949ea2022-09-20 18:38:35 +0200127
128 /* min <= A iff the lowest limb of A is >= min or the other limbs
129 * are not all zero. */
Dave Rodgmanfd7fab42023-05-17 14:00:39 +0100130 return mbedtls_ct_bool_or(msll_mask, min_le_lsl);
Gilles Peskine6f949ea2022-09-20 18:38:35 +0200131}
132
Dave Rodgman8ac9a1d2023-05-17 15:16:22 +0100133mbedtls_ct_condition_t mbedtls_mpi_core_lt_ct(const mbedtls_mpi_uint *A,
134 const mbedtls_mpi_uint *B,
135 size_t limbs)
Dave Rodgman7d4f0192023-05-09 14:01:05 +0100136{
Dave Rodgman8ac9a1d2023-05-17 15:16:22 +0100137 mbedtls_ct_condition_t ret = MBEDTLS_CT_FALSE, cond = MBEDTLS_CT_FALSE, done = MBEDTLS_CT_FALSE;
Dave Rodgman7d4f0192023-05-09 14:01:05 +0100138
139 for (size_t i = limbs; i > 0; i--) {
140 /*
141 * If B[i - 1] < A[i - 1] then A < B is false and the result must
142 * remain 0.
143 *
144 * Again even if we can make a decision, we just mark the result and
145 * the fact that we are done and continue looping.
146 */
Dave Rodgmanb7825ce2023-08-10 11:58:18 +0100147 cond = mbedtls_ct_uint_lt(B[i - 1], A[i - 1]);
Dave Rodgman8ac9a1d2023-05-17 15:16:22 +0100148 done = mbedtls_ct_bool_or(done, cond);
Dave Rodgman7d4f0192023-05-09 14:01:05 +0100149
150 /*
151 * If A[i - 1] < B[i - 1] then A < B is true.
152 *
153 * Again even if we can make a decision, we just mark the result and
154 * the fact that we are done and continue looping.
155 */
Dave Rodgmanb7825ce2023-08-10 11:58:18 +0100156 cond = mbedtls_ct_uint_lt(A[i - 1], B[i - 1]);
Dave Rodgman8ac9a1d2023-05-17 15:16:22 +0100157 ret = mbedtls_ct_bool_or(ret, mbedtls_ct_bool_and(cond, mbedtls_ct_bool_not(done)));
158 done = mbedtls_ct_bool_or(done, cond);
Dave Rodgman7d4f0192023-05-09 14:01:05 +0100159 }
160
161 /*
162 * If all the limbs were equal, then the numbers are equal, A < B is false
163 * and leaving the result 0 is correct.
164 */
165
166 return ret;
Janos Follath3ca07752022-08-09 11:45:47 +0100167}
168
Gilles Peskine449bd832023-01-11 14:50:10 +0100169void mbedtls_mpi_core_cond_assign(mbedtls_mpi_uint *X,
170 const mbedtls_mpi_uint *A,
171 size_t limbs,
Dave Rodgmancd2e38b2023-05-17 13:31:55 +0100172 mbedtls_ct_condition_t assign)
Gabor Mezeie1d31c42022-09-12 16:25:24 +0200173{
Gilles Peskine449bd832023-01-11 14:50:10 +0100174 if (X == A) {
Gabor Mezeie9c013c2022-10-10 14:26:57 +0200175 return;
Gilles Peskine449bd832023-01-11 14:50:10 +0100176 }
Gabor Mezeie9c013c2022-10-10 14:26:57 +0200177
Dave Rodgman3b25c402023-05-18 14:41:06 +0100178 /* This function is very performance-sensitive for RSA. For this reason
179 * we have the loop below, instead of calling mbedtls_ct_memcpy_if
180 * (this is more optimal since here we don't have to handle the case where
181 * we copy awkwardly sized data).
182 */
183 for (size_t i = 0; i < limbs; i++) {
184 X[i] = mbedtls_ct_mpi_uint_if(assign, A[i], X[i]);
185 }
Gabor Mezeie1d31c42022-09-12 16:25:24 +0200186}
187
Gilles Peskine449bd832023-01-11 14:50:10 +0100188void mbedtls_mpi_core_cond_swap(mbedtls_mpi_uint *X,
189 mbedtls_mpi_uint *Y,
190 size_t limbs,
Dave Rodgmancd2e38b2023-05-17 13:31:55 +0100191 mbedtls_ct_condition_t swap)
Gabor Mezeie1d31c42022-09-12 16:25:24 +0200192{
Gilles Peskine449bd832023-01-11 14:50:10 +0100193 if (X == Y) {
Gabor Mezeie9c013c2022-10-10 14:26:57 +0200194 return;
Gilles Peskine449bd832023-01-11 14:50:10 +0100195 }
Gabor Mezeie9c013c2022-10-10 14:26:57 +0200196
Gilles Peskine449bd832023-01-11 14:50:10 +0100197 for (size_t i = 0; i < limbs; i++) {
Gabor Mezeie5b85852022-09-30 13:54:02 +0200198 mbedtls_mpi_uint tmp = X[i];
Dave Rodgmancd2e38b2023-05-17 13:31:55 +0100199 X[i] = mbedtls_ct_mpi_uint_if(swap, Y[i], X[i]);
200 Y[i] = mbedtls_ct_mpi_uint_if(swap, tmp, Y[i]);
Gabor Mezeie1d31c42022-09-12 16:25:24 +0200201 }
Gabor Mezeie1d31c42022-09-12 16:25:24 +0200202}
203
Gilles Peskine449bd832023-01-11 14:50:10 +0100204int mbedtls_mpi_core_read_le(mbedtls_mpi_uint *X,
205 size_t X_limbs,
206 const unsigned char *input,
207 size_t input_length)
Janos Follath3ca07752022-08-09 11:45:47 +0100208{
Gilles Peskine449bd832023-01-11 14:50:10 +0100209 const size_t limbs = CHARS_TO_LIMBS(input_length);
Janos Follath3ca07752022-08-09 11:45:47 +0100210
Gilles Peskine449bd832023-01-11 14:50:10 +0100211 if (X_limbs < limbs) {
212 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
213 }
Janos Follath2ab2d3e2022-08-11 16:13:53 +0100214
Gilles Peskine449bd832023-01-11 14:50:10 +0100215 if (X != NULL) {
216 memset(X, 0, X_limbs * ciL);
Janos Follath3ca07752022-08-09 11:45:47 +0100217
Gilles Peskine449bd832023-01-11 14:50:10 +0100218 for (size_t i = 0; i < input_length; i++) {
219 size_t offset = ((i % ciL) << 3);
220 X[i / ciL] |= ((mbedtls_mpi_uint) input[i]) << offset;
Janos Follathca5688e2022-08-19 12:05:28 +0100221 }
Gabor Mezeibf9da1d2022-08-12 14:11:56 +0200222 }
Janos Follath3ca07752022-08-09 11:45:47 +0100223
Gilles Peskine449bd832023-01-11 14:50:10 +0100224 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +0100225}
226
Gilles Peskine449bd832023-01-11 14:50:10 +0100227int mbedtls_mpi_core_read_be(mbedtls_mpi_uint *X,
228 size_t X_limbs,
229 const unsigned char *input,
230 size_t input_length)
Janos Follath3ca07752022-08-09 11:45:47 +0100231{
Gilles Peskine449bd832023-01-11 14:50:10 +0100232 const size_t limbs = CHARS_TO_LIMBS(input_length);
Janos Follath3ca07752022-08-09 11:45:47 +0100233
Gilles Peskine449bd832023-01-11 14:50:10 +0100234 if (X_limbs < limbs) {
235 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
236 }
Janos Follath2ab2d3e2022-08-11 16:13:53 +0100237
Janos Follathb7a88ec2022-08-19 12:24:40 +0100238 /* If X_limbs is 0, input_length must also be 0 (from previous test).
239 * Nothing to do. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100240 if (X_limbs == 0) {
241 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +0100242 }
243
Gilles Peskine449bd832023-01-11 14:50:10 +0100244 memset(X, 0, X_limbs * ciL);
Gabor Mezeic414ba32022-08-12 17:47:39 +0200245
Gilles Peskine449bd832023-01-11 14:50:10 +0100246 /* memcpy() with (NULL, 0) is undefined behaviour */
247 if (input_length != 0) {
248 size_t overhead = (X_limbs * ciL) - input_length;
249 unsigned char *Xp = (unsigned char *) X;
250 memcpy(Xp + overhead, input, input_length);
251 }
252
253 mbedtls_mpi_core_bigendian_to_host(X, X_limbs);
254
255 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +0100256}
257
Gilles Peskine449bd832023-01-11 14:50:10 +0100258int mbedtls_mpi_core_write_le(const mbedtls_mpi_uint *A,
259 size_t A_limbs,
260 unsigned char *output,
261 size_t output_length)
Janos Follath3ca07752022-08-09 11:45:47 +0100262{
Janos Follathb7a88ec2022-08-19 12:24:40 +0100263 size_t stored_bytes = A_limbs * ciL;
Janos Follath3ca07752022-08-09 11:45:47 +0100264 size_t bytes_to_copy;
Janos Follath3ca07752022-08-09 11:45:47 +0100265
Gilles Peskine449bd832023-01-11 14:50:10 +0100266 if (stored_bytes < output_length) {
Janos Follath3ca07752022-08-09 11:45:47 +0100267 bytes_to_copy = stored_bytes;
Gilles Peskine449bd832023-01-11 14:50:10 +0100268 } else {
Janos Follathb7a88ec2022-08-19 12:24:40 +0100269 bytes_to_copy = output_length;
Janos Follath3ca07752022-08-09 11:45:47 +0100270
Janos Follathaf3f39c2022-08-22 09:06:32 +0100271 /* The output buffer is smaller than the allocated size of A.
Janos Follathb7a88ec2022-08-19 12:24:40 +0100272 * However A may fit if its leading bytes are zero. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100273 for (size_t i = bytes_to_copy; i < stored_bytes; i++) {
274 if (GET_BYTE(A, i) != 0) {
275 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
276 }
Janos Follath3ca07752022-08-09 11:45:47 +0100277 }
278 }
279
Gilles Peskine449bd832023-01-11 14:50:10 +0100280 for (size_t i = 0; i < bytes_to_copy; i++) {
281 output[i] = GET_BYTE(A, i);
Janos Follath3ca07752022-08-09 11:45:47 +0100282 }
283
Gilles Peskine449bd832023-01-11 14:50:10 +0100284 if (stored_bytes < output_length) {
285 /* Write trailing 0 bytes */
286 memset(output + stored_bytes, 0, output_length - stored_bytes);
287 }
288
289 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +0100290}
291
Gilles Peskine449bd832023-01-11 14:50:10 +0100292int mbedtls_mpi_core_write_be(const mbedtls_mpi_uint *X,
293 size_t X_limbs,
294 unsigned char *output,
295 size_t output_length)
Janos Follath3ca07752022-08-09 11:45:47 +0100296{
297 size_t stored_bytes;
298 size_t bytes_to_copy;
299 unsigned char *p;
Janos Follath3ca07752022-08-09 11:45:47 +0100300
Janos Follathb7a88ec2022-08-19 12:24:40 +0100301 stored_bytes = X_limbs * ciL;
Janos Follath3ca07752022-08-09 11:45:47 +0100302
Gilles Peskine449bd832023-01-11 14:50:10 +0100303 if (stored_bytes < output_length) {
Janos Follathaf3f39c2022-08-22 09:06:32 +0100304 /* There is enough space in the output buffer. Write initial
Janos Follath3ca07752022-08-09 11:45:47 +0100305 * null bytes and record the position at which to start
306 * writing the significant bytes. In this case, the execution
307 * trace of this function does not depend on the value of the
308 * number. */
309 bytes_to_copy = stored_bytes;
Janos Follathb7a88ec2022-08-19 12:24:40 +0100310 p = output + output_length - stored_bytes;
Gilles Peskine449bd832023-01-11 14:50:10 +0100311 memset(output, 0, output_length - stored_bytes);
312 } else {
Janos Follathaf3f39c2022-08-22 09:06:32 +0100313 /* The output buffer is smaller than the allocated size of X.
Janos Follath3ca07752022-08-09 11:45:47 +0100314 * However X may fit if its leading bytes are zero. */
Janos Follathb7a88ec2022-08-19 12:24:40 +0100315 bytes_to_copy = output_length;
316 p = output;
Gilles Peskine449bd832023-01-11 14:50:10 +0100317 for (size_t i = bytes_to_copy; i < stored_bytes; i++) {
318 if (GET_BYTE(X, i) != 0) {
319 return MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL;
320 }
Janos Follath3ca07752022-08-09 11:45:47 +0100321 }
322 }
323
Gilles Peskine449bd832023-01-11 14:50:10 +0100324 for (size_t i = 0; i < bytes_to_copy; i++) {
325 p[bytes_to_copy - i - 1] = GET_BYTE(X, i);
326 }
Janos Follath3ca07752022-08-09 11:45:47 +0100327
Gilles Peskine449bd832023-01-11 14:50:10 +0100328 return 0;
Janos Follath3ca07752022-08-09 11:45:47 +0100329}
330
Gilles Peskine449bd832023-01-11 14:50:10 +0100331void mbedtls_mpi_core_shift_r(mbedtls_mpi_uint *X, size_t limbs,
332 size_t count)
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200333{
334 size_t i, v0, v1;
335 mbedtls_mpi_uint r0 = 0, r1;
336
337 v0 = count / biL;
338 v1 = count & (biL - 1);
339
Gilles Peskine449bd832023-01-11 14:50:10 +0100340 if (v0 > limbs || (v0 == limbs && v1 > 0)) {
341 memset(X, 0, limbs * ciL);
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200342 return;
343 }
344
345 /*
346 * shift by count / limb_size
347 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100348 if (v0 > 0) {
349 for (i = 0; i < limbs - v0; i++) {
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200350 X[i] = X[i + v0];
Gilles Peskine449bd832023-01-11 14:50:10 +0100351 }
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200352
Gilles Peskine449bd832023-01-11 14:50:10 +0100353 for (; i < limbs; i++) {
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200354 X[i] = 0;
Gilles Peskine449bd832023-01-11 14:50:10 +0100355 }
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200356 }
357
358 /*
359 * shift by count % limb_size
360 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100361 if (v1 > 0) {
362 for (i = limbs; i > 0; i--) {
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200363 r1 = X[i - 1] << (biL - v1);
364 X[i - 1] >>= v1;
365 X[i - 1] |= r0;
366 r0 = r1;
367 }
368 }
369}
370
Minos Galanakisec09e252023-04-20 14:22:16 +0100371void mbedtls_mpi_core_shift_l(mbedtls_mpi_uint *X, size_t limbs,
372 size_t count)
Minos Galanakisad808dd2023-04-20 12:18:41 +0100373{
Minos Galanakisec09e252023-04-20 14:22:16 +0100374 size_t i, v0, v1;
Minos Galanakisad808dd2023-04-20 12:18:41 +0100375 mbedtls_mpi_uint r0 = 0, r1;
Minos Galanakisad808dd2023-04-20 12:18:41 +0100376
Minos Galanakisec09e252023-04-20 14:22:16 +0100377 v0 = count / (biL);
378 v1 = count & (biL - 1);
Minos Galanakisad808dd2023-04-20 12:18:41 +0100379
Minos Galanakisad808dd2023-04-20 12:18:41 +0100380 /*
381 * shift by count / limb_size
382 */
Minos Galanakisec09e252023-04-20 14:22:16 +0100383 if (v0 > 0) {
384 for (i = limbs; i > v0; i--) {
385 X[i - 1] = X[i - v0 - 1];
386 }
Minos Galanakisad808dd2023-04-20 12:18:41 +0100387
Minos Galanakisec09e252023-04-20 14:22:16 +0100388 for (; i > 0; i--) {
389 X[i - 1] = 0;
390 }
Minos Galanakisad808dd2023-04-20 12:18:41 +0100391 }
392
393 /*
394 * shift by count % limb_size
395 */
Minos Galanakisec09e252023-04-20 14:22:16 +0100396 if (v1 > 0) {
397 for (i = v0; i < limbs; i++) {
398 r1 = X[i] >> (biL - v1);
399 X[i] <<= v1;
400 X[i] |= r0;
Minos Galanakisad808dd2023-04-20 12:18:41 +0100401 r0 = r1;
402 }
403 }
Minos Galanakisad808dd2023-04-20 12:18:41 +0100404}
405
Gilles Peskine449bd832023-01-11 14:50:10 +0100406mbedtls_mpi_uint mbedtls_mpi_core_add(mbedtls_mpi_uint *X,
407 const mbedtls_mpi_uint *A,
408 const mbedtls_mpi_uint *B,
409 size_t limbs)
Hanno Beckerc9887132022-08-24 12:54:36 +0100410{
Tom Cosgroveaf7d44b2022-08-24 14:05:26 +0100411 mbedtls_mpi_uint c = 0;
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200412
Gilles Peskine449bd832023-01-11 14:50:10 +0100413 for (size_t i = 0; i < limbs; i++) {
Tom Cosgroveaf7d44b2022-08-24 14:05:26 +0100414 mbedtls_mpi_uint t = c + A[i];
Gilles Peskine449bd832023-01-11 14:50:10 +0100415 c = (t < A[i]);
Tom Cosgroveaf7d44b2022-08-24 14:05:26 +0100416 t += B[i];
Gilles Peskine449bd832023-01-11 14:50:10 +0100417 c += (t < B[i]);
Tom Cosgroveaf7d44b2022-08-24 14:05:26 +0100418 X[i] = t;
Hanno Beckerc9887132022-08-24 12:54:36 +0100419 }
Tom Cosgroveaf7d44b2022-08-24 14:05:26 +0100420
Gilles Peskine449bd832023-01-11 14:50:10 +0100421 return c;
Hanno Beckerc9887132022-08-24 12:54:36 +0100422}
Gilles Peskinec279b2f2022-09-21 15:38:38 +0200423
Gilles Peskine449bd832023-01-11 14:50:10 +0100424mbedtls_mpi_uint mbedtls_mpi_core_add_if(mbedtls_mpi_uint *X,
425 const mbedtls_mpi_uint *A,
426 size_t limbs,
427 unsigned cond)
Tom Cosgroveb4964862022-08-30 11:57:22 +0100428{
Tom Cosgrovef0c8a8c2022-08-30 15:15:02 +0100429 mbedtls_mpi_uint c = 0;
430
Dave Rodgmanb59b73e2023-05-17 15:17:12 +0100431 mbedtls_ct_condition_t do_add = mbedtls_ct_bool(cond);
Tom Cosgrove93549902022-08-30 17:41:23 +0100432
Gilles Peskine449bd832023-01-11 14:50:10 +0100433 for (size_t i = 0; i < limbs; i++) {
Dave Rodgman98ddc012023-08-10 12:11:31 +0100434 mbedtls_mpi_uint add = mbedtls_ct_mpi_uint_if_else_0(do_add, A[i]);
Tom Cosgrove3bd7bc32022-09-15 15:55:07 +0100435 mbedtls_mpi_uint t = c + X[i];
Gilles Peskine449bd832023-01-11 14:50:10 +0100436 c = (t < X[i]);
Tom Cosgrovef0c8a8c2022-08-30 15:15:02 +0100437 t += add;
Gilles Peskine449bd832023-01-11 14:50:10 +0100438 c += (t < add);
Tom Cosgrove3bd7bc32022-09-15 15:55:07 +0100439 X[i] = t;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100440 }
Tom Cosgrovef0c8a8c2022-08-30 15:15:02 +0100441
Gilles Peskine449bd832023-01-11 14:50:10 +0100442 return c;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100443}
444
Gilles Peskine449bd832023-01-11 14:50:10 +0100445mbedtls_mpi_uint mbedtls_mpi_core_sub(mbedtls_mpi_uint *X,
446 const mbedtls_mpi_uint *A,
447 const mbedtls_mpi_uint *B,
448 size_t limbs)
Tom Cosgroveb4964862022-08-30 11:57:22 +0100449{
450 mbedtls_mpi_uint c = 0;
451
Gilles Peskine449bd832023-01-11 14:50:10 +0100452 for (size_t i = 0; i < limbs; i++) {
453 mbedtls_mpi_uint z = (A[i] < c);
Tom Cosgroveb4964862022-08-30 11:57:22 +0100454 mbedtls_mpi_uint t = A[i] - c;
Gilles Peskine449bd832023-01-11 14:50:10 +0100455 c = (t < B[i]) + z;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100456 X[i] = t - B[i];
457 }
458
Gilles Peskine449bd832023-01-11 14:50:10 +0100459 return c;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100460}
461
Gilles Peskine449bd832023-01-11 14:50:10 +0100462mbedtls_mpi_uint mbedtls_mpi_core_mla(mbedtls_mpi_uint *d, size_t d_len,
463 const mbedtls_mpi_uint *s, size_t s_len,
464 mbedtls_mpi_uint b)
Tom Cosgroveb4964862022-08-30 11:57:22 +0100465{
466 mbedtls_mpi_uint c = 0; /* carry */
Tom Cosgrove5dd97e62022-08-30 14:31:49 +0100467 /*
468 * It is a documented precondition of this function that d_len >= s_len.
469 * If that's not the case, we swap these round: this turns what would be
470 * a buffer overflow into an incorrect result.
471 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100472 if (d_len < s_len) {
Tom Cosgroveb4964862022-08-30 11:57:22 +0100473 s_len = d_len;
Gilles Peskine449bd832023-01-11 14:50:10 +0100474 }
Tom Cosgroveb4964862022-08-30 11:57:22 +0100475 size_t excess_len = d_len - s_len;
476 size_t steps_x8 = s_len / 8;
477 size_t steps_x1 = s_len & 7;
478
Gilles Peskine449bd832023-01-11 14:50:10 +0100479 while (steps_x8--) {
Tom Cosgroveb4964862022-08-30 11:57:22 +0100480 MULADDC_X8_INIT
481 MULADDC_X8_CORE
Gilles Peskine449bd832023-01-11 14:50:10 +0100482 MULADDC_X8_STOP
Tom Cosgroveb4964862022-08-30 11:57:22 +0100483 }
484
Gilles Peskine449bd832023-01-11 14:50:10 +0100485 while (steps_x1--) {
Tom Cosgroveb4964862022-08-30 11:57:22 +0100486 MULADDC_X1_INIT
487 MULADDC_X1_CORE
Gilles Peskine449bd832023-01-11 14:50:10 +0100488 MULADDC_X1_STOP
Tom Cosgroveb4964862022-08-30 11:57:22 +0100489 }
490
Gilles Peskine449bd832023-01-11 14:50:10 +0100491 while (excess_len--) {
Tom Cosgrovef0c8a8c2022-08-30 15:15:02 +0100492 *d += c;
Gilles Peskine449bd832023-01-11 14:50:10 +0100493 c = (*d < c);
Tom Cosgrovef0c8a8c2022-08-30 15:15:02 +0100494 d++;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100495 }
496
Gilles Peskine449bd832023-01-11 14:50:10 +0100497 return c;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100498}
499
Tom Cosgrove6af26f32022-08-24 16:40:55 +0100500void mbedtls_mpi_core_mul(mbedtls_mpi_uint *X,
501 const mbedtls_mpi_uint *A, size_t A_limbs,
502 const mbedtls_mpi_uint *B, size_t B_limbs)
Hanno Becker4ae890b2022-08-24 16:17:52 +0100503{
Tom Cosgrove6af26f32022-08-24 16:40:55 +0100504 memset(X, 0, (A_limbs + B_limbs) * ciL);
505
506 for (size_t i = 0; i < B_limbs; i++) {
507 (void) mbedtls_mpi_core_mla(X + i, A_limbs + 1, A, A_limbs, B[i]);
508 }
Hanno Becker4ae890b2022-08-24 16:17:52 +0100509}
510
Tom Cosgroveb4964862022-08-30 11:57:22 +0100511/*
512 * Fast Montgomery initialization (thanks to Tom St Denis).
513 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100514mbedtls_mpi_uint mbedtls_mpi_core_montmul_init(const mbedtls_mpi_uint *N)
Tom Cosgroveb4964862022-08-30 11:57:22 +0100515{
516 mbedtls_mpi_uint x = N[0];
517
Gilles Peskine449bd832023-01-11 14:50:10 +0100518 x += ((N[0] + 2) & 4) << 1;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100519
Gilles Peskine449bd832023-01-11 14:50:10 +0100520 for (unsigned int i = biL; i >= 8; i /= 2) {
521 x *= (2 - (N[0] * x));
522 }
Tom Cosgroveb4964862022-08-30 11:57:22 +0100523
Gilles Peskine449bd832023-01-11 14:50:10 +0100524 return ~x + 1;
Tom Cosgroveb4964862022-08-30 11:57:22 +0100525}
526
Gilles Peskine449bd832023-01-11 14:50:10 +0100527void mbedtls_mpi_core_montmul(mbedtls_mpi_uint *X,
528 const mbedtls_mpi_uint *A,
529 const mbedtls_mpi_uint *B,
530 size_t B_limbs,
531 const mbedtls_mpi_uint *N,
532 size_t AN_limbs,
533 mbedtls_mpi_uint mm,
534 mbedtls_mpi_uint *T)
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100535{
Gilles Peskine449bd832023-01-11 14:50:10 +0100536 memset(T, 0, (2 * AN_limbs + 1) * ciL);
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100537
Gilles Peskine449bd832023-01-11 14:50:10 +0100538 for (size_t i = 0; i < AN_limbs; i++) {
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100539 /* T = (T + u0*B + u1*N) / 2^biL */
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100540 mbedtls_mpi_uint u0 = A[i];
Gilles Peskine449bd832023-01-11 14:50:10 +0100541 mbedtls_mpi_uint u1 = (T[0] + u0 * B[0]) * mm;
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100542
Gilles Peskine449bd832023-01-11 14:50:10 +0100543 (void) mbedtls_mpi_core_mla(T, AN_limbs + 2, B, B_limbs, u0);
544 (void) mbedtls_mpi_core_mla(T, AN_limbs + 2, N, AN_limbs, u1);
Tom Cosgrove67c92472022-09-02 13:28:59 +0100545
546 T++;
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100547 }
548
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100549 /*
550 * The result we want is (T >= N) ? T - N : T.
551 *
552 * For better constant-time properties in this function, we always do the
553 * subtraction, with the result in X.
554 *
555 * We also look to see if there was any carry in the final additions in the
556 * loop above.
557 */
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100558
Tom Cosgrove72594632022-08-24 11:51:58 +0100559 mbedtls_mpi_uint carry = T[AN_limbs];
Gilles Peskine449bd832023-01-11 14:50:10 +0100560 mbedtls_mpi_uint borrow = mbedtls_mpi_core_sub(X, T, N, AN_limbs);
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100561
562 /*
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100563 * Using R as the Montgomery radix (auxiliary modulus) i.e. 2^(biL*AN_limbs):
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100564 *
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100565 * T can be in one of 3 ranges:
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100566 *
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100567 * 1) T < N : (carry, borrow) = (0, 1): we want T
568 * 2) N <= T < R : (carry, borrow) = (0, 0): we want X
569 * 3) T >= R : (carry, borrow) = (1, 1): we want X
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100570 *
Tom Cosgrovef0b22312022-08-31 17:57:34 +0100571 * and (carry, borrow) = (1, 0) can't happen.
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100572 *
573 * So the correct return value is already in X if (carry ^ borrow) = 0,
Tom Cosgrove72594632022-08-24 11:51:58 +0100574 * but is in (the lower AN_limbs limbs of) T if (carry ^ borrow) = 1.
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100575 */
Dave Rodgman231a5162023-05-17 15:13:14 +0100576 mbedtls_ct_memcpy_if(mbedtls_ct_bool(carry ^ borrow),
577 (unsigned char *) X,
578 (unsigned char *) T,
579 NULL,
580 AN_limbs * sizeof(mbedtls_mpi_uint));
Tom Cosgrove958fd3d2022-08-24 11:08:51 +0100581}
582
Gilles Peskine449bd832023-01-11 14:50:10 +0100583int mbedtls_mpi_core_get_mont_r2_unsafe(mbedtls_mpi *X,
584 const mbedtls_mpi *N)
Hanno Beckerec440f22022-08-11 17:29:32 +0100585{
586 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
587
Gilles Peskine449bd832023-01-11 14:50:10 +0100588 MBEDTLS_MPI_CHK(mbedtls_mpi_lset(X, 1));
589 MBEDTLS_MPI_CHK(mbedtls_mpi_shift_l(X, N->n * 2 * biL));
590 MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(X, X, N));
591 MBEDTLS_MPI_CHK(mbedtls_mpi_shrink(X, N->n));
Hanno Beckerec440f22022-08-11 17:29:32 +0100592
593cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100594 return ret;
Hanno Beckerec440f22022-08-11 17:29:32 +0100595}
596
Janos Follath59cbd1b2022-10-28 18:13:43 +0100597MBEDTLS_STATIC_TESTABLE
Gilles Peskine449bd832023-01-11 14:50:10 +0100598void mbedtls_mpi_core_ct_uint_table_lookup(mbedtls_mpi_uint *dest,
599 const mbedtls_mpi_uint *table,
600 size_t limbs,
601 size_t count,
602 size_t index)
Janos Follathe50f2f12022-10-26 15:14:33 +0100603{
Gilles Peskine449bd832023-01-11 14:50:10 +0100604 for (size_t i = 0; i < count; i++, table += limbs) {
Dave Rodgmanb7825ce2023-08-10 11:58:18 +0100605 mbedtls_ct_condition_t assign = mbedtls_ct_uint_eq(i, index);
Gilles Peskine449bd832023-01-11 14:50:10 +0100606 mbedtls_mpi_core_cond_assign(dest, table, limbs, assign);
Janos Follathe50f2f12022-10-26 15:14:33 +0100607 }
608}
609
Gilles Peskine009d1952022-09-09 21:00:00 +0200610/* Fill X with n_bytes random bytes.
611 * X must already have room for those bytes.
612 * The ordering of the bytes returned from the RNG is suitable for
Gilles Peskine22cdd0c2022-10-27 20:15:13 +0200613 * deterministic ECDSA (see RFC 6979 §3.3 and the specification of
614 * mbedtls_mpi_core_random()).
Gilles Peskine009d1952022-09-09 21:00:00 +0200615 */
616int mbedtls_mpi_core_fill_random(
617 mbedtls_mpi_uint *X, size_t X_limbs,
618 size_t n_bytes,
Gilles Peskine449bd832023-01-11 14:50:10 +0100619 int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
Gilles Peskine009d1952022-09-09 21:00:00 +0200620{
621 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
Gilles Peskine449bd832023-01-11 14:50:10 +0100622 const size_t limbs = CHARS_TO_LIMBS(n_bytes);
623 const size_t overhead = (limbs * ciL) - n_bytes;
Gilles Peskine009d1952022-09-09 21:00:00 +0200624
Gilles Peskine449bd832023-01-11 14:50:10 +0100625 if (X_limbs < limbs) {
626 return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
627 }
Gilles Peskine009d1952022-09-09 21:00:00 +0200628
Gilles Peskine449bd832023-01-11 14:50:10 +0100629 memset(X, 0, overhead);
630 memset((unsigned char *) X + limbs * ciL, 0, (X_limbs - limbs) * ciL);
631 MBEDTLS_MPI_CHK(f_rng(p_rng, (unsigned char *) X + overhead, n_bytes));
632 mbedtls_mpi_core_bigendian_to_host(X, limbs);
Gilles Peskine009d1952022-09-09 21:00:00 +0200633
634cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100635 return ret;
Gilles Peskine009d1952022-09-09 21:00:00 +0200636}
637
Gilles Peskine449bd832023-01-11 14:50:10 +0100638int mbedtls_mpi_core_random(mbedtls_mpi_uint *X,
639 mbedtls_mpi_uint min,
640 const mbedtls_mpi_uint *N,
641 size_t limbs,
642 int (*f_rng)(void *, unsigned char *, size_t),
643 void *p_rng)
Gilles Peskine70375b22022-09-21 15:47:23 +0200644{
Dave Rodgmanfd492ab2023-05-17 15:17:29 +0100645 mbedtls_ct_condition_t ge_lower = MBEDTLS_CT_TRUE, lt_upper = MBEDTLS_CT_FALSE;
Gilles Peskine449bd832023-01-11 14:50:10 +0100646 size_t n_bits = mbedtls_mpi_core_bitlen(N, limbs);
647 size_t n_bytes = (n_bits + 7) / 8;
Gilles Peskine70375b22022-09-21 15:47:23 +0200648 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
649
650 /*
651 * When min == 0, each try has at worst a probability 1/2 of failing
652 * (the msb has a probability 1/2 of being 0, and then the result will
653 * be < N), so after 30 tries failure probability is a most 2**(-30).
654 *
655 * When N is just below a power of 2, as is the case when generating
656 * a random scalar on most elliptic curves, 1 try is enough with
657 * overwhelming probability. When N is just above a power of 2,
658 * as when generating a random scalar on secp224k1, each try has
659 * a probability of failing that is almost 1/2.
660 *
661 * The probabilities are almost the same if min is nonzero but negligible
662 * compared to N. This is always the case when N is crypto-sized, but
663 * it's convenient to support small N for testing purposes. When N
664 * is small, use a higher repeat count, otherwise the probability of
665 * failure is macroscopic.
666 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100667 int count = (n_bytes > 4 ? 30 : 250);
Gilles Peskine70375b22022-09-21 15:47:23 +0200668
669 /*
670 * Match the procedure given in RFC 6979 §3.3 (deterministic ECDSA)
671 * when f_rng is a suitably parametrized instance of HMAC_DRBG:
672 * - use the same byte ordering;
673 * - keep the leftmost n_bits bits of the generated octet string;
674 * - try until result is in the desired range.
675 * This also avoids any bias, which is especially important for ECDSA.
676 */
Gilles Peskine449bd832023-01-11 14:50:10 +0100677 do {
678 MBEDTLS_MPI_CHK(mbedtls_mpi_core_fill_random(X, limbs,
679 n_bytes,
680 f_rng, p_rng));
681 mbedtls_mpi_core_shift_r(X, limbs, 8 * n_bytes - n_bits);
Gilles Peskine70375b22022-09-21 15:47:23 +0200682
Gilles Peskine449bd832023-01-11 14:50:10 +0100683 if (--count == 0) {
Gilles Peskine70375b22022-09-21 15:47:23 +0200684 ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
685 goto cleanup;
686 }
687
Gilles Peskine449bd832023-01-11 14:50:10 +0100688 ge_lower = mbedtls_mpi_core_uint_le_mpi(min, X, limbs);
689 lt_upper = mbedtls_mpi_core_lt_ct(X, N, limbs);
Dave Rodgmanfd492ab2023-05-17 15:17:29 +0100690 } while (mbedtls_ct_bool_and(ge_lower, lt_upper) == MBEDTLS_CT_FALSE);
Gilles Peskine70375b22022-09-21 15:47:23 +0200691
692cleanup:
Gilles Peskine449bd832023-01-11 14:50:10 +0100693 return ret;
Gilles Peskine70375b22022-09-21 15:47:23 +0200694}
695
Gilles Peskine449bd832023-01-11 14:50:10 +0100696static size_t exp_mod_get_window_size(size_t Ebits)
Janos Follathb6673f02022-09-30 14:13:14 +0100697{
Dave Rodgman4883f102023-08-09 20:17:40 +0100698#if MBEDTLS_MPI_WINDOW_SIZE >= 6
699 return (Ebits > 671) ? 6 : (Ebits > 239) ? 5 : (Ebits > 79) ? 4 : 1;
700#elif MBEDTLS_MPI_WINDOW_SIZE == 5
701 return (Ebits > 239) ? 5 : (Ebits > 79) ? 4 : 1;
702#elif MBEDTLS_MPI_WINDOW_SIZE > 1
703 return (Ebits > 79) ? MBEDTLS_MPI_WINDOW_SIZE : 1;
704#else
705 (void) Ebits;
706 return 1;
Janos Follathb6673f02022-09-30 14:13:14 +0100707#endif
Janos Follathb6673f02022-09-30 14:13:14 +0100708}
709
Gilles Peskine449bd832023-01-11 14:50:10 +0100710size_t mbedtls_mpi_core_exp_mod_working_limbs(size_t AN_limbs, size_t E_limbs)
Tom Cosgrove0a0dded2022-12-06 14:37:18 +0000711{
Gilles Peskine449bd832023-01-11 14:50:10 +0100712 const size_t wsize = exp_mod_get_window_size(E_limbs * biL);
713 const size_t welem = ((size_t) 1) << wsize;
Tom Cosgrove0a0dded2022-12-06 14:37:18 +0000714
715 /* How big does each part of the working memory pool need to be? */
716 const size_t table_limbs = welem * AN_limbs;
717 const size_t select_limbs = AN_limbs;
718 const size_t temp_limbs = 2 * AN_limbs + 1;
719
Gilles Peskine449bd832023-01-11 14:50:10 +0100720 return table_limbs + select_limbs + temp_limbs;
Tom Cosgrove0a0dded2022-12-06 14:37:18 +0000721}
722
Gilles Peskine449bd832023-01-11 14:50:10 +0100723static void exp_mod_precompute_window(const mbedtls_mpi_uint *A,
724 const mbedtls_mpi_uint *N,
725 size_t AN_limbs,
726 mbedtls_mpi_uint mm,
727 const mbedtls_mpi_uint *RR,
728 size_t welem,
729 mbedtls_mpi_uint *Wtable,
730 mbedtls_mpi_uint *temp)
Gilles Peskine0de0a042022-11-16 20:12:49 +0100731{
Gilles Peskine0de0a042022-11-16 20:12:49 +0100732 /* W[0] = 1 (in Montgomery presentation) */
Gilles Peskine449bd832023-01-11 14:50:10 +0100733 memset(Wtable, 0, AN_limbs * ciL);
Gilles Peskine0de0a042022-11-16 20:12:49 +0100734 Wtable[0] = 1;
Gilles Peskine449bd832023-01-11 14:50:10 +0100735 mbedtls_mpi_core_montmul(Wtable, Wtable, RR, AN_limbs, N, AN_limbs, mm, temp);
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100736
Tom Cosgroveecda1862022-12-06 10:46:30 +0000737 /* W[1] = A (already in Montgomery presentation) */
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100738 mbedtls_mpi_uint *W1 = Wtable + AN_limbs;
Gilles Peskine449bd832023-01-11 14:50:10 +0100739 memcpy(W1, A, AN_limbs * ciL);
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100740
Gilles Peskine0de0a042022-11-16 20:12:49 +0100741 /* W[i+1] = W[i] * W[1], i >= 2 */
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100742 mbedtls_mpi_uint *Wprev = W1;
Gilles Peskine449bd832023-01-11 14:50:10 +0100743 for (size_t i = 2; i < welem; i++) {
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100744 mbedtls_mpi_uint *Wcur = Wprev + AN_limbs;
Gilles Peskine449bd832023-01-11 14:50:10 +0100745 mbedtls_mpi_core_montmul(Wcur, Wprev, W1, AN_limbs, N, AN_limbs, mm, temp);
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100746 Wprev = Wcur;
747 }
Gilles Peskine0de0a042022-11-16 20:12:49 +0100748}
749
Janos Follath8786dd72024-08-20 10:21:54 +0100750#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
Janos Follath96cfd7a2024-08-22 18:30:06 +0100751void (*mbedtls_safe_codepath_hook)(void) = NULL;
752void (*mbedtls_unsafe_codepath_hook)(void) = NULL;
Janos Follatha1126912024-08-20 09:56:16 +0100753#endif
754
Janos Follathbb3f2952024-08-12 19:05:47 +0100755/*
756 * This function calculates the indices of the exponent where the exponentiation algorithm should
757 * start processing.
758 *
759 * Warning! If the parameter E_public has MBEDTLS_MPI_IS_PUBLIC as its value,
760 * this function is not constant time with respect to the exponent (parameter E).
761 */
762static inline void exp_mod_calc_first_bit_optionally_safe(const mbedtls_mpi_uint *E,
763 size_t E_limbs,
764 int E_public,
765 size_t *E_limb_index,
766 size_t *E_bit_index)
767{
768 if (E_public == MBEDTLS_MPI_IS_PUBLIC) {
Janos Follathafb20792024-08-20 10:41:55 +0100769 /*
770 * Skip leading zero bits.
771 */
Janos Follathbb3f2952024-08-12 19:05:47 +0100772 size_t E_bits = mbedtls_mpi_core_bitlen(E, E_limbs);
Janos Follathafb20792024-08-20 10:41:55 +0100773 if (E_bits == 0) {
774 /*
775 * If E is 0 mbedtls_mpi_core_bitlen() returns 0. Even if that is the case, we will want
776 * to represent it as a single 0 bit and as such the bitlength will be 1.
777 */
778 E_bits = 1;
Janos Follathbb3f2952024-08-12 19:05:47 +0100779 }
Janos Follathafb20792024-08-20 10:41:55 +0100780
781 *E_limb_index = E_bits / biL;
782 *E_bit_index = E_bits % biL;
783
Janos Follath8786dd72024-08-20 10:21:54 +0100784#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200785 if (mbedtls_unsafe_codepath_hook != NULL) {
Janos Follath96cfd7a2024-08-22 18:30:06 +0100786 mbedtls_unsafe_codepath_hook();
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200787 }
Janos Follathe0842aa2024-08-13 08:40:31 +0100788#endif
Janos Follathbb3f2952024-08-12 19:05:47 +0100789 } else {
790 /*
791 * Here we need to be constant time with respect to E and can't do anything better than
792 * start at the first allocated bit.
793 */
794 *E_limb_index = E_limbs;
795 *E_bit_index = 0;
Janos Follath8786dd72024-08-20 10:21:54 +0100796#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200797 if (mbedtls_safe_codepath_hook != NULL) {
Janos Follath96cfd7a2024-08-22 18:30:06 +0100798 mbedtls_safe_codepath_hook();
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200799 }
Janos Follathe0842aa2024-08-13 08:40:31 +0100800#endif
Janos Follathbb3f2952024-08-12 19:05:47 +0100801 }
802}
803
804/*
805 * Warning! If the parameter window_public has MBEDTLS_MPI_IS_PUBLIC as its value, this function is
806 * not constant time with respect to the window parameter and consequently the exponent of the
807 * exponentiation (parameter E of mbedtls_mpi_core_exp_mod_optionally_safe).
808 */
809static inline void exp_mod_table_lookup_optionally_safe(mbedtls_mpi_uint *Wselect,
810 mbedtls_mpi_uint *Wtable,
811 size_t AN_limbs, size_t welem,
812 mbedtls_mpi_uint window,
813 int window_public)
814{
815 if (window_public == MBEDTLS_MPI_IS_PUBLIC) {
816 memcpy(Wselect, Wtable + window * AN_limbs, AN_limbs * ciL);
Janos Follath8786dd72024-08-20 10:21:54 +0100817#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200818 if (mbedtls_unsafe_codepath_hook != NULL) {
Janos Follath96cfd7a2024-08-22 18:30:06 +0100819 mbedtls_unsafe_codepath_hook();
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200820 }
Janos Follathe0842aa2024-08-13 08:40:31 +0100821#endif
Janos Follathbb3f2952024-08-12 19:05:47 +0100822 } else {
823 /* Select Wtable[window] without leaking window through
824 * memory access patterns. */
825 mbedtls_mpi_core_ct_uint_table_lookup(Wselect, Wtable,
826 AN_limbs, welem, window);
Janos Follath8786dd72024-08-20 10:21:54 +0100827#if defined(MBEDTLS_TEST_HOOKS) && !defined(MBEDTLS_THREADING_C)
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200828 if (mbedtls_safe_codepath_hook != NULL) {
Janos Follath96cfd7a2024-08-22 18:30:06 +0100829 mbedtls_safe_codepath_hook();
Manuel Pégourié-Gonnard126cfed2024-09-02 10:42:46 +0200830 }
Janos Follathe0842aa2024-08-13 08:40:31 +0100831#endif
Janos Follathbb3f2952024-08-12 19:05:47 +0100832 }
833}
834
Gilles Peskine7d89d352022-11-16 22:54:14 +0100835/* Exponentiation: X := A^E mod N.
836 *
Janos Follath38ff70e2024-08-12 18:20:59 +0100837 * Warning! If the parameter E_public has MBEDTLS_MPI_IS_PUBLIC as its value,
838 * this function is not constant time with respect to the exponent (parameter E).
839 *
Tom Cosgroveecda1862022-12-06 10:46:30 +0000840 * A must already be in Montgomery form.
841 *
Gilles Peskine7d89d352022-11-16 22:54:14 +0100842 * As in other bignum functions, assume that AN_limbs and E_limbs are nonzero.
843 *
844 * RR must contain 2^{2*biL} mod N.
Janos Follath3321b582022-11-22 21:08:33 +0000845 *
846 * The algorithm is a variant of Left-to-right k-ary exponentiation: HAC 14.82
847 * (The difference is that the body in our loop processes a single bit instead
848 * of a full window.)
Gilles Peskine7d89d352022-11-16 22:54:14 +0100849 */
Janos Follath38ff70e2024-08-12 18:20:59 +0100850static void mbedtls_mpi_core_exp_mod_optionally_safe(mbedtls_mpi_uint *X,
851 const mbedtls_mpi_uint *A,
852 const mbedtls_mpi_uint *N,
853 size_t AN_limbs,
854 const mbedtls_mpi_uint *E,
855 size_t E_limbs,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100856 int E_public,
Janos Follath38ff70e2024-08-12 18:20:59 +0100857 const mbedtls_mpi_uint *RR,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100858 mbedtls_mpi_uint *T)
Janos Follathb6673f02022-09-30 14:13:14 +0100859{
Janos Follath020b9ab2024-08-13 07:53:20 +0100860 /* We'll process the bits of E from most significant
861 * (limb_index=E_limbs-1, E_bit_index=biL-1) to least significant
862 * (limb_index=0, E_bit_index=0). */
Janos Follathe86607c2024-08-22 17:07:58 +0100863 size_t E_limb_index = E_limbs;
864 size_t E_bit_index = 0;
Janos Follath020b9ab2024-08-13 07:53:20 +0100865 exp_mod_calc_first_bit_optionally_safe(E, E_limbs, E_public,
866 &E_limb_index, &E_bit_index);
867
868 const size_t wsize = exp_mod_get_window_size(E_limb_index * biL);
Gilles Peskine449bd832023-01-11 14:50:10 +0100869 const size_t welem = ((size_t) 1) << wsize;
Janos Follathb6673f02022-09-30 14:13:14 +0100870
Tom Cosgrove0a0dded2022-12-06 14:37:18 +0000871 /* This is how we will use the temporary storage T, which must have space
872 * for table_limbs, select_limbs and (2 * AN_limbs + 1) for montmul. */
873 const size_t table_limbs = welem * AN_limbs;
874 const size_t select_limbs = AN_limbs;
Janos Follathb6673f02022-09-30 14:13:14 +0100875
Tom Cosgrove0a0dded2022-12-06 14:37:18 +0000876 /* Pointers to specific parts of the temporary working memory pool */
877 mbedtls_mpi_uint *const Wtable = T;
878 mbedtls_mpi_uint *const Wselect = Wtable + table_limbs;
879 mbedtls_mpi_uint *const temp = Wselect + select_limbs;
Janos Follathb6673f02022-09-30 14:13:14 +0100880
881 /*
882 * Window precomputation
883 */
884
Gilles Peskine449bd832023-01-11 14:50:10 +0100885 const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N);
Gilles Peskinecf979b02022-11-16 20:04:00 +0100886
Janos Follath2c624412024-08-15 15:53:07 +0100887 /* Set Wtable[i] = A^i (in Montgomery representation) */
Gilles Peskine449bd832023-01-11 14:50:10 +0100888 exp_mod_precompute_window(A, N, AN_limbs,
889 mm, RR,
890 welem, Wtable, temp);
Janos Follathb6673f02022-09-30 14:13:14 +0100891
892 /*
Janos Follath0ec6e3f2022-11-14 12:52:08 +0000893 * Fixed window exponentiation
Janos Follathb6673f02022-09-30 14:13:14 +0100894 */
895
896 /* X = 1 (in Montgomery presentation) initially */
Gilles Peskine449bd832023-01-11 14:50:10 +0100897 memcpy(X, Wtable, AN_limbs * ciL);
Janos Follathb6673f02022-09-30 14:13:14 +0100898
Gilles Peskine0b270a52022-11-16 22:54:03 +0100899 /* At any given time, window contains window_bits bits from E.
900 * window_bits can go up to wsize. */
Janos Follathbad42c42022-11-09 14:30:44 +0000901 size_t window_bits = 0;
Gilles Peskine0b270a52022-11-16 22:54:03 +0100902 mbedtls_mpi_uint window = 0;
Gilles Peskinecf979b02022-11-16 20:04:00 +0100903
Gilles Peskine449bd832023-01-11 14:50:10 +0100904 do {
Janos Follathb6673f02022-09-30 14:13:14 +0100905 /* Square */
Gilles Peskine449bd832023-01-11 14:50:10 +0100906 mbedtls_mpi_core_montmul(X, X, X, AN_limbs, N, AN_limbs, mm, temp);
Janos Follathb6673f02022-09-30 14:13:14 +0100907
Janos Follath3321b582022-11-22 21:08:33 +0000908 /* Move to the next bit of the exponent */
Gilles Peskine449bd832023-01-11 14:50:10 +0100909 if (E_bit_index == 0) {
Gilles Peskinec718a3c2022-11-16 20:42:09 +0100910 --E_limb_index;
911 E_bit_index = biL - 1;
Gilles Peskine449bd832023-01-11 14:50:10 +0100912 } else {
Gilles Peskinec718a3c2022-11-16 20:42:09 +0100913 --E_bit_index;
914 }
Janos Follath3321b582022-11-22 21:08:33 +0000915 /* Insert next exponent bit into window */
Gilles Peskined83b5cb2022-11-16 20:26:14 +0100916 ++window_bits;
Gilles Peskinec718a3c2022-11-16 20:42:09 +0100917 window <<= 1;
Gilles Peskine449bd832023-01-11 14:50:10 +0100918 window |= (E[E_limb_index] >> E_bit_index) & 1;
Gilles Peskine3b63d092022-11-16 22:06:18 +0100919
920 /* Clear window if it's full. Also clear the window at the end,
921 * when we've finished processing the exponent. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100922 if (window_bits == wsize ||
923 (E_bit_index == 0 && E_limb_index == 0)) {
Janos Follathbb3f2952024-08-12 19:05:47 +0100924
925 exp_mod_table_lookup_optionally_safe(Wselect, Wtable, AN_limbs, welem,
926 window, E_public);
Gilles Peskine0b270a52022-11-16 22:54:03 +0100927 /* Multiply X by the selected element. */
Gilles Peskine449bd832023-01-11 14:50:10 +0100928 mbedtls_mpi_core_montmul(X, X, Wselect, AN_limbs, N, AN_limbs, mm,
929 temp);
Gilles Peskine3b63d092022-11-16 22:06:18 +0100930 window = 0;
931 window_bits = 0;
932 }
Gilles Peskine449bd832023-01-11 14:50:10 +0100933 } while (!(E_bit_index == 0 && E_limb_index == 0));
Janos Follathb6673f02022-09-30 14:13:14 +0100934}
935
Manuel Pégourié-Gonnard75ed5872024-06-18 12:52:45 +0200936void mbedtls_mpi_core_exp_mod(mbedtls_mpi_uint *X,
937 const mbedtls_mpi_uint *A,
938 const mbedtls_mpi_uint *N, size_t AN_limbs,
939 const mbedtls_mpi_uint *E, size_t E_limbs,
940 const mbedtls_mpi_uint *RR,
941 mbedtls_mpi_uint *T)
942{
943 mbedtls_mpi_core_exp_mod_optionally_safe(X,
944 A,
945 N,
946 AN_limbs,
947 E,
948 E_limbs,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100949 MBEDTLS_MPI_IS_SECRET,
Manuel Pégourié-Gonnard75ed5872024-06-18 12:52:45 +0200950 RR,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100951 T);
Manuel Pégourié-Gonnard75ed5872024-06-18 12:52:45 +0200952}
953
Janos Follath38ff70e2024-08-12 18:20:59 +0100954void mbedtls_mpi_core_exp_mod_unsafe(mbedtls_mpi_uint *X,
955 const mbedtls_mpi_uint *A,
956 const mbedtls_mpi_uint *N, size_t AN_limbs,
957 const mbedtls_mpi_uint *E, size_t E_limbs,
958 const mbedtls_mpi_uint *RR,
959 mbedtls_mpi_uint *T)
960{
961 mbedtls_mpi_core_exp_mod_optionally_safe(X,
962 A,
963 N,
964 AN_limbs,
965 E,
966 E_limbs,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100967 MBEDTLS_MPI_IS_PUBLIC,
Janos Follath38ff70e2024-08-12 18:20:59 +0100968 RR,
Janos Follatha5fc8f32024-08-12 20:11:06 +0100969 T);
Janos Follath38ff70e2024-08-12 18:20:59 +0100970}
971
Gilles Peskine449bd832023-01-11 14:50:10 +0100972mbedtls_mpi_uint mbedtls_mpi_core_sub_int(mbedtls_mpi_uint *X,
973 const mbedtls_mpi_uint *A,
974 mbedtls_mpi_uint c, /* doubles as carry */
975 size_t limbs)
Hanno Beckerd9b23482022-08-25 08:25:19 +0100976{
Gilles Peskine449bd832023-01-11 14:50:10 +0100977 for (size_t i = 0; i < limbs; i++) {
Tom Cosgrovef7ff4c92022-08-25 08:39:07 +0100978 mbedtls_mpi_uint s = A[i];
979 mbedtls_mpi_uint t = s - c;
Gilles Peskine449bd832023-01-11 14:50:10 +0100980 c = (t > s);
Tom Cosgrovef7ff4c92022-08-25 08:39:07 +0100981 X[i] = t;
Hanno Beckerd9b23482022-08-25 08:25:19 +0100982 }
983
Gilles Peskine449bd832023-01-11 14:50:10 +0100984 return c;
Hanno Beckerd9b23482022-08-25 08:25:19 +0100985}
986
Janos Follathadb9d2d2024-03-11 10:03:05 +0000987mbedtls_ct_condition_t mbedtls_mpi_core_check_zero_ct(const mbedtls_mpi_uint *A,
Janos Follathaec1a862024-02-21 11:24:20 +0000988 size_t limbs)
Tom Cosgrove30f3b4d2022-12-12 16:54:57 +0000989{
Janos Follath23dc8b52024-03-11 10:39:57 +0000990 volatile const mbedtls_mpi_uint *force_read_A = A;
Janos Follathd6df0a52024-03-11 09:40:03 +0000991 mbedtls_mpi_uint bits = 0;
Tom Cosgrove30f3b4d2022-12-12 16:54:57 +0000992
Gilles Peskine449bd832023-01-11 14:50:10 +0100993 for (size_t i = 0; i < limbs; i++) {
Janos Follathadb9d2d2024-03-11 10:03:05 +0000994 bits |= force_read_A[i];
Gilles Peskine449bd832023-01-11 14:50:10 +0100995 }
Tom Cosgrove30f3b4d2022-12-12 16:54:57 +0000996
Janos Follathaec1a862024-02-21 11:24:20 +0000997 return mbedtls_ct_bool(bits);
Tom Cosgrove30f3b4d2022-12-12 16:54:57 +0000998}
999
Gilles Peskine449bd832023-01-11 14:50:10 +01001000void mbedtls_mpi_core_to_mont_rep(mbedtls_mpi_uint *X,
1001 const mbedtls_mpi_uint *A,
1002 const mbedtls_mpi_uint *N,
1003 size_t AN_limbs,
1004 mbedtls_mpi_uint mm,
1005 const mbedtls_mpi_uint *rr,
1006 mbedtls_mpi_uint *T)
Tom Cosgrove786848b2022-12-13 10:45:19 +00001007{
Gilles Peskine449bd832023-01-11 14:50:10 +01001008 mbedtls_mpi_core_montmul(X, A, rr, AN_limbs, N, AN_limbs, mm, T);
Tom Cosgrove786848b2022-12-13 10:45:19 +00001009}
1010
Gilles Peskine449bd832023-01-11 14:50:10 +01001011void mbedtls_mpi_core_from_mont_rep(mbedtls_mpi_uint *X,
1012 const mbedtls_mpi_uint *A,
1013 const mbedtls_mpi_uint *N,
1014 size_t AN_limbs,
1015 mbedtls_mpi_uint mm,
1016 mbedtls_mpi_uint *T)
Tom Cosgrove786848b2022-12-13 10:45:19 +00001017{
1018 const mbedtls_mpi_uint Rinv = 1; /* 1/R in Mont. rep => 1 */
1019
Gilles Peskine449bd832023-01-11 14:50:10 +01001020 mbedtls_mpi_core_montmul(X, A, &Rinv, 1, N, AN_limbs, mm, T);
Tom Cosgrove786848b2022-12-13 10:45:19 +00001021}
1022
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001023/*
1024 * Compute X = A - B mod N.
1025 * Both A and B must be in [0, N) and so will the output.
1026 */
1027static void mpi_core_sub_mod(mbedtls_mpi_uint *X,
1028 const mbedtls_mpi_uint *A,
1029 const mbedtls_mpi_uint *B,
1030 const mbedtls_mpi_uint *N,
1031 size_t limbs)
1032{
1033 mbedtls_mpi_uint c = mbedtls_mpi_core_sub(X, A, B, limbs);
1034 (void) mbedtls_mpi_core_add_if(X, N, limbs, (unsigned) c);
1035}
1036
1037/*
1038 * Divide X by 2 mod N in place, assuming N is odd.
1039 * The input must be in [0, N) and so will the output.
1040 */
Manuel Pégourié-Gonnard7fba4662025-07-17 09:17:12 +02001041MBEDTLS_STATIC_TESTABLE
1042void mbedtls_mpi_core_div2_mod_odd(mbedtls_mpi_uint *X,
1043 const mbedtls_mpi_uint *N,
1044 size_t limbs)
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001045{
1046 /* If X is odd, add N to make it even before shifting. */
1047 unsigned odd = (unsigned) X[0] & 1;
1048 mbedtls_mpi_uint c = mbedtls_mpi_core_add_if(X, N, limbs, odd);
1049 mbedtls_mpi_core_shift_r(X, limbs, 1);
1050 X[limbs - 1] |= c << (biL - 1);
1051}
1052
1053/*
1054 * Constant-time GCD and modular inversion - odd modulus.
1055 *
1056 * Pre-conditions: see public documentation.
1057 *
1058 * See https://www.jstage.jst.go.jp/article/transinf/E106.D/9/E106.D_2022ICP0009/_pdf
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001059 *
1060 * The paper gives two computationally equivalent algorithms: Alg 7 (readable)
1061 * and Alg 8 (constant-time). We use a third version that's hopefully both:
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001062 *
1063 * u, v = A, N # N is called p in the paper but doesn't have to be prime
1064 * q, r = 0, 1
1065 * repeat bits(A_limbs + N_limbs) times:
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001066 * d = v - u # t1 in Alg 7
1067 * t1 = (u and v both odd) ? u : d # t1 in Alg 8
1068 * t2 = (u and v both odd) ? d : (u odd) ? v : u # t2 in Alg 8
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001069 * t2 >>= 1
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001070 * swap = t1 > t2 # similar to s, z in Alg 8
1071 * u, v = (swap) ? t2, t1 : t1, t2
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001072 *
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001073 * d = r - q mod N # t2 in Alg 7
1074 * t1 = (u and v both odd) ? q : d # t3 in Alg 8
1075 * t2 = (u and v both odd) ? d : (u odd) ? r : q # t4 Alg 8
1076 * t2 /= 2 mod N # see below (pre_com)
1077 * q, r = (swap) ? t2, t1 : t1, t2
1078 * return v, q # v: GCD, see Alg 6; q: no mult by pre_com, see below
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001079 *
1080 * The ternary operators in the above pseudo-code need to be realised in a
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001081 * constant-time fashion. We use conditional assign for t1, t2 and conditional
1082 * swap for the final update. (Note: the similarity between branches of Alg 7
1083 * are highlighted in tables 2 and 3 and the surrounding text.)
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001084 *
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001085 * Also, we re-order operations, grouping things related to the inverse, which
1086 * facilitates making its computation optional, and requires fewer temporaries.
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001087 *
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001088 * The only actual change from the paper is dropping the trick with pre_com,
Manuel Pégourié-Gonnard93615502025-07-23 13:21:07 +02001089 * which I think complicates things for no benefit.
1090 * See the comment on the big I != NULL block below for details.
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001091 */
1092void mbedtls_mpi_core_gcd_modinv_odd(mbedtls_mpi_uint *G,
1093 mbedtls_mpi_uint *I,
1094 const mbedtls_mpi_uint *A,
1095 size_t A_limbs,
1096 const mbedtls_mpi_uint *N,
1097 size_t N_limbs,
1098 mbedtls_mpi_uint *T)
1099{
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001100 /* GCD and modinv, names common to Alg 7 and Alg 8 */
1101 mbedtls_mpi_uint *u = T + 0 * N_limbs;
1102 mbedtls_mpi_uint *v = G;
1103
1104 /* GCD and modinv, my name (t1, t2 from Alg 7) */
1105 mbedtls_mpi_uint *d = T + 1 * N_limbs;
1106
1107 /* GCD and modinv, names from Alg 8 (note: t1, t2 from Alg 7 are d above) */
1108 mbedtls_mpi_uint *t1 = T + 2 * N_limbs;
1109 mbedtls_mpi_uint *t2 = T + 3 * N_limbs;
1110
1111 /* modinv only, names common to Alg 7 and Alg 8 */
1112 mbedtls_mpi_uint *q = I;
1113 mbedtls_mpi_uint *r = I != NULL ? T + 4 * N_limbs : NULL;
1114
1115 /*
1116 * Initial values:
1117 * u, v = A, N
1118 * q, r = 0, 1
Manuel Pégourié-Gonnardde5eeb52025-07-15 12:12:36 +02001119 *
1120 * We only write to G (aka v) after reading from inputs (A and N), which
1121 * allows aliasing, except with N when I != NULL, as then we'll be operating
1122 * mod N on q and r later - see the public documentation.
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001123 */
Manuel Pégourié-Gonnardefd242a2025-07-24 11:10:59 +02001124 if (A_limbs > N_limbs) {
1125 /* Violating this precondition should not result in memory errors. */
1126 A_limbs = N_limbs;
1127 }
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001128 memcpy(u, A, A_limbs * ciL);
1129 memset((char *) u + A_limbs * ciL, 0, (N_limbs - A_limbs) * ciL);
1130
Manuel Pégourié-Gonnardefd242a2025-07-24 11:10:59 +02001131 /* Avoid possible UB with memcpy when src == dst. */
Manuel Pégourié-Gonnardde5eeb52025-07-15 12:12:36 +02001132 if (v != N) {
1133 memcpy(v, N, N_limbs * ciL);
1134 }
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001135
1136 if (I != NULL) {
1137 memset(q, 0, N_limbs * ciL);
1138
1139 memset(r, 0, N_limbs * ciL);
1140 r[0] = 1;
1141 }
1142
1143 /*
1144 * At each step, out of u, v, v - u we keep one, shift another, and discard
1145 * the third, then update (u, v) with the ordered result.
1146 * Then we mirror those actions with q, r, r - q mod N.
1147 *
1148 * Loop invariants:
1149 * u <= v (on entry: A <= N)
1150 * GCD(u, v) == GCD(A, N) (on entry: trivial)
1151 * v = A * q mod N (on entry: N = A * 0 mod N)
1152 * u = A * r mod N (on entry: A = A * 1 mod N)
1153 * q, r in [0, N) (on entry: 0, 1)
1154 *
1155 * On exit:
1156 * u = 0
1157 * v = GCD(A, N) = A * q mod N
1158 * if v == 1 then 1 = A * q mod N ie q is A's inverse mod N
1159 * r = 0
1160 *
1161 * The exit state is a fixed point of the loop's body.
1162 * Alg 7 and Alg 8 use 2 * bitlen(N) iterations but Theorem 2 (above in the
1163 * paper) says bitlen(A) + bitlen(N) is actually enough.
1164 */
1165 for (size_t i = 0; i < (A_limbs + N_limbs) * biL; i++) {
1166 /* s, z in Alg 8 - use meaningful names instead */
1167 mbedtls_ct_condition_t u_odd = mbedtls_ct_bool(u[0] & 1);
1168 mbedtls_ct_condition_t v_odd = mbedtls_ct_bool(v[0] & 1);
1169
1170 /* Other conditions that will be useful below */
1171 mbedtls_ct_condition_t u_odd_v_odd = mbedtls_ct_bool_and(u_odd, v_odd);
1172 mbedtls_ct_condition_t v_even = mbedtls_ct_bool_not(v_odd);
1173 mbedtls_ct_condition_t u_odd_v_even = mbedtls_ct_bool_and(u_odd, v_even);
1174
1175 /* This is called t1 in Alg 7 (no name in Alg 8).
1176 * We know that u <= v so there is no carry */
1177 (void) mbedtls_mpi_core_sub(d, v, u, N_limbs);
1178
1179 /* t1 (the thing that's kept) can be d (default) or u (if t2 is d) */
1180 memcpy(t1, d, N_limbs * ciL);
1181 mbedtls_mpi_core_cond_assign(t1, u, N_limbs, u_odd_v_odd);
1182
1183 /* t2 (the thing that's shifted) can be u (if even), or v (if even),
1184 * or d (which is even if both u and v were odd) */
1185 memcpy(t2, u, N_limbs * ciL);
1186 mbedtls_mpi_core_cond_assign(t2, v, N_limbs, u_odd_v_even);
1187 mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);
1188
1189 mbedtls_mpi_core_shift_r(t2, N_limbs, 1); // t2 is even
1190
1191 /* Update u, v and re-order them if needed */
1192 memcpy(u, t1, N_limbs * ciL);
1193 memcpy(v, t2, N_limbs * ciL);
1194 mbedtls_ct_condition_t swap = mbedtls_mpi_core_lt_ct(v, u, N_limbs);
1195 mbedtls_mpi_core_cond_swap(u, v, N_limbs, swap);
1196
1197 /* Now, if modinv was requested, do the same with q, r, but:
1198 * - decisions still based on u and v (their initial values);
1199 * - operations are now mod N;
1200 * - we re-use t1, t2 for what the paper calls t3, t4 in Alg 8.
1201 *
1202 * Here we slightly diverge from the paper and instead do the obvious
1203 * thing that preserves the invariants involving q and r: mirror
1204 * operations on u and v, ie also divide by 2 here (mod N).
1205 *
1206 * The paper uses a trick where it replaces division by 2 with
Manuel Pégourié-Gonnardec353822025-07-24 12:22:16 +02001207 * multiplication by 2 here, and compensates in the end by multiplying
1208 * by pre_com, which is probably intended as an optimisation.
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001209 *
1210 * However I believe it's not actually an optimisation, since
1211 * constant-time modular multiplication by 2 (left-shift + conditional
1212 * subtract) is just as costly as constant-time modular division by 2
1213 * (conditional add + right-shift). So, skip it and keep things simple.
1214 */
1215 if (I != NULL) {
1216 /* This is called t2 in Alg 7 (no name in Alg 8). */
1217 mpi_core_sub_mod(d, q, r, N, N_limbs);
1218
1219 /* t3 (the thing that's kept) */
1220 memcpy(t1, d, N_limbs * ciL);
1221 mbedtls_mpi_core_cond_assign(t1, r, N_limbs, u_odd_v_odd);
1222
1223 /* t4 (the thing that's shifted) */
1224 memcpy(t2, r, N_limbs * ciL);
1225 mbedtls_mpi_core_cond_assign(t2, q, N_limbs, u_odd_v_even);
1226 mbedtls_mpi_core_cond_assign(t2, d, N_limbs, u_odd_v_odd);
1227
Manuel Pégourié-Gonnard7fba4662025-07-17 09:17:12 +02001228 mbedtls_mpi_core_div2_mod_odd(t2, N, N_limbs);
Manuel Pégourié-Gonnard07a05772025-07-09 10:42:28 +02001229
1230 /* Update and possibly swap */
1231 memcpy(r, t1, N_limbs * ciL);
1232 memcpy(q, t2, N_limbs * ciL);
1233 mbedtls_mpi_core_cond_swap(r, q, N_limbs, swap);
1234 }
1235 }
1236
1237 /* G and I already hold the correct values by virtue of being aliased */
1238}
1239
Janos Follath3ca07752022-08-09 11:45:47 +01001240#endif /* MBEDTLS_BIGNUM_C */