Mbed TLS is now part of TrustedFirmware.org.

HMAC-SHA256 implementation without dynamic mem allocation


Apr 24, 2018 07:54
David Reimondez Garcia

Hi!

we need to calculate the HMAC-SHA256 for a project but we are not allowed to use dynamic memory. Therefore I modified the already existing function "mbedtls_md_hmac" included in "md.c" like this. Could you give me feedback about it? Do you see any risks?

Thanks a lot!

int hmac_calculateSHA256(   const unsigned char *key, size_t keylen,
                            const unsigned char *input, size_t ilen,
                            unsigned char *output   )
{
    const mbedtls_md_info_t *md_info = &mbedtls_sha256_info;
    mbedtls_md_context_t ctx;
    int ret;

    mbedtls_md_init( &ctx );

    // This code implements mbedtls_md_setup without dynamic memory
    unsigned char mdCtx[sizeof(mbedtls_sha256_context)] = {0};      // originally in mbedtls_md_setup
    unsigned char hmacCtx[2 * HMAC_BLOCK_SIZE] = {0};                   // originally in md2_ctx_alloc( void )

    // Link to the context
    ctx.md_ctx = &mdCtx;
    ctx.hmac_ctx = &hmacCtx;
    ctx.md_info = md_info;

    // Perform calculation
    if( ( ret = mbedtls_md_hmac_starts( &ctx, key, keylen ) ) != 0 )
        goto cleanup;
    if( ( ret = mbedtls_md_hmac_update( &ctx, input, ilen ) ) != 0 )
        goto cleanup;
    if( ( ret = mbedtls_md_hmac_finish( &ctx, output ) ) != 0 )
        goto cleanup;

cleanup:
    // Use this function instead of memset to avoid compiler optimization
    zeroize( mdCtx, sizeof(mbedtls_sha256_context) );
    zeroize(&hmacCtx, 2 * HMAC_BLOCK_SIZE);
    zeroize( &ctx, sizeof( mbedtls_md_context_t ) );

    return( ret );
}
 
Apr 24, 2018 08:30
Ron Eldor

Hi David,
Have you considered using the MBEDTLS_MEMORY_BUFFER_ALLOC_C feature as described in this KB?
Regards,
Mbed TLS Team member
Ron