From 2f2b396b7a2b3999894569843894febc6b313d9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Manuel=20P=C3=A9gouri=C3=A9-Gonnard?= Date: Mon, 12 Nov 2018 15:06:57 +0100 Subject: [PATCH] Add new macro to detemine ECDSA signature length Revived from a previous PR by Gilles, see: https://github.com/ARMmbed/mbedtls/pull/1293/files#diff-568ef321d275f2035b8b26a70ee9af0bR71 This will be useful in eliminating temporary stack buffers for transcoding the signature: in order to do that in place we need to be able to make assumptions about the size of the output buffer, which this macro will provide. (See next commit.) --- include/mbedtls/ecdsa.h | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/include/mbedtls/ecdsa.h b/include/mbedtls/ecdsa.h index 4057828d4..5245c6ee3 100644 --- a/include/mbedtls/ecdsa.h +++ b/include/mbedtls/ecdsa.h @@ -35,25 +35,30 @@ #include "ecp.h" #include "md.h" -/* - * RFC-4492 page 20: +/** + * \brief Maximum ECDSA signature size for a given curve bit size * + * \param bits Curve size in bits + * \return Maximum signature size in bytes + * + * \note This macro returns a compile-time constant if its argument + * is one. It may evaluate its argument multiple times. + */ +/* * Ecdsa-Sig-Value ::= SEQUENCE { * r INTEGER, * s INTEGER * } * - * Size is at most - * 1 (tag) + 1 (len) + 1 (initial 0) + ECP_MAX_BYTES for each of r and s, - * twice that + 1 (tag) + 2 (len) for the sequence - * (assuming ECP_MAX_BYTES is less than 126 for r and s, - * and less than 124 (total len <= 255) for the sequence) + * For each of r and s, the value (V) may include an extra initial "0" bit. */ -#if MBEDTLS_ECP_MAX_BYTES > 124 -#error "MBEDTLS_ECP_MAX_BYTES bigger than expected, please fix MBEDTLS_ECDSA_MAX_LEN" -#endif +#define MBEDTLS_ECDSA_MAX_SIG_LEN( bits ) \ + ( /*T,L of SEQUENCE*/ ( ( bits ) >= 61 * 8 ? 3 : 2 ) + \ + /*T,L of r,s*/ 2 * ( ( ( bits ) >= 127 * 8 ? 3 : 2 ) + \ + /*V of r,s*/ ( ( bits ) + 8 ) / 8 ) ) + /** The maximal size of an ECDSA signature in Bytes. */ -#define MBEDTLS_ECDSA_MAX_LEN ( 3 + 2 * ( 3 + MBEDTLS_ECP_MAX_BYTES ) ) +#define MBEDTLS_ECDSA_MAX_LEN MBEDTLS_ECDSA_MAX_SIG_LEN( MBEDTLS_ECP_MAX_BITS ) #ifdef __cplusplus extern "C" {