diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h index 3ba177799d..eb8446ea88 100644 --- a/include/mbedtls/bignum.h +++ b/include/mbedtls/bignum.h @@ -186,6 +186,15 @@ typedef uint64_t mbedtls_t_udbl; #endif /* !MBEDTLS_NO_UDBL_DIVISION */ #endif /* !MBEDTLS_HAVE_INT64 */ +/* + * Sanity check that exactly one of MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64 is defined, + * so that code elsewhere doesn't have to check. + */ +#if (!(defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64))) || \ + (defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)) +#error "Only 32-bit or 64-bit limbs are supported in bignum" +#endif + /** \typedef mbedtls_mpi_uint * \brief The type of machine digits in a bignum, called _limbs_. * diff --git a/library/bignum_core.c b/library/bignum_core.c index 48b640bdb9..dbf6d1df46 100644 --- a/library/bignum_core.c +++ b/library/bignum_core.c @@ -77,38 +77,17 @@ size_t mbedtls_mpi_core_bitlen(const mbedtls_mpi_uint *A, size_t A_limbs) return 0; } -/* Convert a big-endian byte array aligned to the size of mbedtls_mpi_uint - * into the storage form used by mbedtls_mpi. */ -static mbedtls_mpi_uint mpi_bigendian_to_host_c(mbedtls_mpi_uint a) -{ - uint8_t i; - unsigned char *a_ptr; - mbedtls_mpi_uint tmp = 0; - - for (i = 0, a_ptr = (unsigned char *) &a; i < ciL; i++, a_ptr++) { - tmp <<= CHAR_BIT; - tmp |= (mbedtls_mpi_uint) *a_ptr; - } - - return tmp; -} - static mbedtls_mpi_uint mpi_bigendian_to_host(mbedtls_mpi_uint a) { if (MBEDTLS_IS_BIG_ENDIAN) { /* Nothing to do on bigendian systems. */ return a; } else { - switch (sizeof(mbedtls_mpi_uint)) { - case 4: - return (mbedtls_mpi_uint) MBEDTLS_BSWAP32((uint32_t) a); - case 8: - return (mbedtls_mpi_uint) MBEDTLS_BSWAP64((uint64_t) a); - } - - /* Fall back to C-based reordering if we don't know the byte order - * or we couldn't use a compiler-specific builtin. */ - return mpi_bigendian_to_host_c(a); +#if defined(MBEDTLS_HAVE_INT32) + return (mbedtls_mpi_uint) MBEDTLS_BSWAP32(a); +#elif defined(MBEDTLS_HAVE_INT64) + return (mbedtls_mpi_uint) MBEDTLS_BSWAP64(a); +#endif } } diff --git a/library/x509_crt.c b/library/x509_crt.c index 2cbced210e..8d07694a2c 100644 --- a/library/x509_crt.c +++ b/library/x509_crt.c @@ -2754,8 +2754,8 @@ static int x509_inet_pton_ipv6(const char *src, void *dst) p++; } if (num_digits != 0) { - addr[nonzero_groups++] = MBEDTLS_IS_BIG_ENDIAN ? group : - (group << 8) | (group >> 8); + MBEDTLS_PUT_UINT16_BE(group, addr, nonzero_groups); + nonzero_groups++; if (*p == '\0') { break; } else if (*p == '.') {