blob: 35173b9e7b0ad1ad3303820f3f0928544b3a8a03 [file] [log] [blame]
Janos Follath3ca07752022-08-09 11:45:47 +01001/*
2 * Multi-precision integer library
3 *
4 * Copyright The Mbed TLS Contributors
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20#include "common.h"
21
22#if defined(MBEDTLS_BIGNUM_C)
23
24#include <string.h>
25
26#include "mbedtls/error.h"
27#include "mbedtls/platform_util.h"
28
29#if defined(MBEDTLS_PLATFORM_C)
30#include "mbedtls/platform.h"
31#else
32#include <stdio.h>
33#include <stdlib.h>
34#define mbedtls_printf printf
35#define mbedtls_calloc calloc
36#define mbedtls_free free
37#endif
38
39#include "bignum_core.h"
40
41#define MPI_VALIDATE_RET( cond ) \
42 MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_MPI_BAD_INPUT_DATA )
43#define MPI_VALIDATE( cond ) \
44 MBEDTLS_INTERNAL_VALIDATE( cond )
45
46#define ciL (sizeof(mbedtls_mpi_uint)) /* chars in limb */
47#define biL (ciL << 3) /* bits in limb */
48#define biH (ciL << 2) /* half limb size */
49
50/*
51 * Convert between bits/chars and number of limbs
52 * Divide first in order to avoid potential overflows
53 */
54#define BITS_TO_LIMBS(i) ( (i) / biL + ( (i) % biL != 0 ) )
55#define CHARS_TO_LIMBS(i) ( (i) / ciL + ( (i) % ciL != 0 ) )
56/* Get a specific byte, without range checks. */
57#define GET_BYTE( X, i ) \
58 ( ( ( X )[( i ) / ciL] >> ( ( ( i ) % ciL ) * 8 ) ) & 0xff )
59
60/*
61 * Count leading zero bits in a given integer
62 */
63size_t mbedtls_mpi_core_clz( const mbedtls_mpi_uint x )
64{
65 size_t j;
66 mbedtls_mpi_uint mask = (mbedtls_mpi_uint) 1 << (biL - 1);
67
68 for( j = 0; j < biL; j++ )
69 {
70 if( x & mask ) break;
71
72 mask >>= 1;
73 }
74
75 return j;
76}
77
78/*
79 * Return the number of bits
80 */
81size_t mbedtls_mpi_core_bitlen( const mbedtls_mpi_uint *X, size_t nx )
82{
83 size_t i, j;
84
85 if( nx == 0 )
86 return( 0 );
87
88 for( i = nx - 1; i > 0; i-- )
89 if( X[i] != 0 )
90 break;
91
92 j = biL - mbedtls_mpi_core_clz( X[i] );
93
94 return( ( i * biL ) + j );
95}
96
97/* Check X to have at least n limbs and set it to 0. */
98static int mpi_core_clear( mbedtls_mpi_uint *X,
99 size_t nx,
100 size_t limbs )
101{
102 if( nx < limbs )
103 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
104
105 if( X != NULL )
106 memset( X, 0, nx * ciL );
107
108 return( 0 );
109}
110
111/* Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint
112 * into the storage form used by mbedtls_mpi. */
113static mbedtls_mpi_uint mpi_bigendian_to_host_c( mbedtls_mpi_uint x )
114{
115 uint8_t i;
116 unsigned char *x_ptr;
117 mbedtls_mpi_uint tmp = 0;
118
119 for( i = 0, x_ptr = (unsigned char*) &x; i < ciL; i++, x_ptr++ )
120 {
121 tmp <<= CHAR_BIT;
122 tmp |= (mbedtls_mpi_uint) *x_ptr;
123 }
124
125 return( tmp );
126}
127
128static mbedtls_mpi_uint mpi_bigendian_to_host( mbedtls_mpi_uint x )
129{
130#if defined(__BYTE_ORDER__)
131
132/* Nothing to do on bigendian systems. */
133#if ( __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ )
134 return( x );
135#endif /* __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ */
136
137#if ( __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ )
138
139/* For GCC and Clang, have builtins for byte swapping. */
140#if defined(__GNUC__) && defined(__GNUC_PREREQ)
141#if __GNUC_PREREQ(4,3)
142#define have_bswap
143#endif
144#endif
145
146#if defined(__clang__) && defined(__has_builtin)
147#if __has_builtin(__builtin_bswap32) && \
148 __has_builtin(__builtin_bswap64)
149#define have_bswap
150#endif
151#endif
152
153#if defined(have_bswap)
154 /* The compiler is hopefully able to statically evaluate this! */
155 switch( sizeof(mbedtls_mpi_uint) )
156 {
157 case 4:
158 return( __builtin_bswap32(x) );
159 case 8:
160 return( __builtin_bswap64(x) );
161 }
162#endif
163#endif /* __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ */
164#endif /* __BYTE_ORDER__ */
165
166 /* Fall back to C-based reordering if we don't know the byte order
167 * or we couldn't use a compiler-specific builtin. */
168 return( mpi_bigendian_to_host_c( x ) );
169}
170
171void mbedtls_mpi_core_bigendian_to_host( mbedtls_mpi_uint * const X,
172 size_t limbs )
173{
174 mbedtls_mpi_uint *cur_limb_left;
175 mbedtls_mpi_uint *cur_limb_right;
176 if( limbs == 0 )
177 return;
178
179 /*
180 * Traverse limbs and
181 * - adapt byte-order in each limb
182 * - swap the limbs themselves.
183 * For that, simultaneously traverse the limbs from left to right
184 * and from right to left, as long as the left index is not bigger
185 * than the right index (it's not a problem if limbs is odd and the
186 * indices coincide in the last iteration).
187 */
188 for( cur_limb_left = X, cur_limb_right = X + ( limbs - 1 );
189 cur_limb_left <= cur_limb_right;
190 cur_limb_left++, cur_limb_right-- )
191 {
192 mbedtls_mpi_uint tmp;
193 /* Note that if cur_limb_left == cur_limb_right,
194 * this code effectively swaps the bytes only once. */
195 tmp = mpi_bigendian_to_host( *cur_limb_left );
196 *cur_limb_left = mpi_bigendian_to_host( *cur_limb_right );
197 *cur_limb_right = tmp;
198 }
199}
200
201/*
202 * Import X from unsigned binary data, little endian
203 *
204 * The MPI needs to have enough limbs to store the full value (in particular,
205 * this function does not skip 0s in the input).
206 */
207int mbedtls_mpi_core_read_le( mbedtls_mpi_uint *X,
208 size_t nx,
209 const unsigned char *buf,
210 size_t buflen )
211{
212 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
213 size_t i;
214 size_t const limbs = CHARS_TO_LIMBS( buflen );
215
216 /* Ensure that target MPI has at least the necessary number of limbs */
217 MBEDTLS_MPI_CHK( mpi_core_clear( X, nx, limbs ) );
218
219 for( i = 0; i < buflen; i++ )
220 X[i / ciL] |= ((mbedtls_mpi_uint) buf[i]) << ((i % ciL) << 3);
221
222cleanup:
223 return( ret );
224}
225
226/*
227 * Import X from unsigned binary data, big endian
228 *
229 * The MPI needs to have enough limbs to store the full value (in particular,
230 * this function does not skip 0s in the input).
231 */
232int mbedtls_mpi_core_read_be( mbedtls_mpi_uint *X,
233 size_t nx,
234 const unsigned char *buf,
235 size_t buflen )
236{
237 int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
238 size_t const limbs = CHARS_TO_LIMBS( buflen );
239 size_t overhead;
240 unsigned char *Xp;
241
242 MPI_VALIDATE_RET( X != NULL );
243 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
244
245 /* Ensure that target MPI has at least the necessary number of limbs */
246 MBEDTLS_MPI_CHK( mpi_core_clear( X, nx, limbs ) );
247
248 overhead = ( nx * ciL ) - buflen;
249
250 /* Avoid calling `memcpy` with NULL source or destination argument,
251 * even if buflen is 0. */
252 if( buflen != 0 )
253 {
254 Xp = (unsigned char*) X;
255 memcpy( Xp + overhead, buf, buflen );
256
257 mbedtls_mpi_core_bigendian_to_host( X, nx );
258 }
259
260cleanup:
261 return( ret );
262}
263
264/*
265 * Export X into unsigned binary data, little endian
266 */
267int mbedtls_mpi_core_write_le( const mbedtls_mpi_uint *X,
268 size_t nx,
269 unsigned char *buf,
270 size_t buflen )
271{
272 size_t stored_bytes = nx * ciL;
273 size_t bytes_to_copy;
274 size_t i;
275
276 if( stored_bytes < buflen )
277 {
278 bytes_to_copy = stored_bytes;
279 }
280 else
281 {
282 bytes_to_copy = buflen;
283
284 /* The output buffer is smaller than the allocated size of X.
285 * However X may fit if its leading bytes are zero. */
286 for( i = bytes_to_copy; i < stored_bytes; i++ )
287 {
288 if( GET_BYTE( X, i ) != 0 )
289 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
290 }
291 }
292
293 for( i = 0; i < bytes_to_copy; i++ )
294 buf[i] = GET_BYTE( X, i );
295
296 if( stored_bytes < buflen )
297 {
298 /* Write trailing 0 bytes */
299 memset( buf + stored_bytes, 0, buflen - stored_bytes );
300 }
301
302 return( 0 );
303}
304
305/*
306 * Export X into unsigned binary data, big endian
307 */
308int mbedtls_mpi_core_write_be( const mbedtls_mpi_uint *X,
309 size_t nx,
310 unsigned char *buf,
311 size_t buflen )
312{
313 size_t stored_bytes;
314 size_t bytes_to_copy;
315 unsigned char *p;
316 size_t i;
317
318 MPI_VALIDATE_RET( X != NULL );
319 MPI_VALIDATE_RET( buflen == 0 || buf != NULL );
320
321 stored_bytes = nx * ciL;
322
323 if( stored_bytes < buflen )
324 {
325 /* There is enough space in the output buffer. Write initial
326 * null bytes and record the position at which to start
327 * writing the significant bytes. In this case, the execution
328 * trace of this function does not depend on the value of the
329 * number. */
330 bytes_to_copy = stored_bytes;
331 p = buf + buflen - stored_bytes;
332 memset( buf, 0, buflen - stored_bytes );
333 }
334 else
335 {
336 /* The output buffer is smaller than the allocated size of X.
337 * However X may fit if its leading bytes are zero. */
338 bytes_to_copy = buflen;
339 p = buf;
340 for( i = bytes_to_copy; i < stored_bytes; i++ )
341 {
342 if( GET_BYTE( X, i ) != 0 )
343 return( MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL );
344 }
345 }
346
347 for( i = 0; i < bytes_to_copy; i++ )
348 p[bytes_to_copy - i - 1] = GET_BYTE( X, i );
349
350 return( 0 );
351}
352
353#endif /* MBEDTLS_BIGNUM_C */