Arm Mbed and Pelion Device Management support forum

Mbedtls_sha256 gives the wrong result

Hello, I am having troubles with computing the sha256 using mbedtls functions. I’ll try to explain the problem the best as I can:

I have two memory segments, let’s call them A and B. In segment A I have stored all the
mbedtls functions, but now I need to call theese functions from B, and in particular I need to
compute the sha256 of a certain string. For this purpose I have made a test calling the starts, update and finish functions as follows:

//Segment B

int ret = 0;
char* data = “123456789”;
uint8_t hash[32] = {0};
mbedtls_sha256_context ctx;

ret = mbedtls_sha256_starts_ret( &ctx, 0 );
ret = mbedtls_sha256_update_ret( &ctx, data, 9 );
ret = mbedtls_sha256_finish_ret( &ctx, hash );

The result contained in hash is completely different from what it should be.
I have tried to do the same thing in segment A and the result is correct instead. So I was doing some debugging just to understand what was going wrong in segment B, and I discovered that the contex ctx is initialized and updated properly, but at some point in the finish it happens that something different is written in the state[] part of the context (the rest is exactly the same as in segment A), and I don’t understand why. It seems that something wrong happens into the mbedtls_internal_sha256_process() function, but I don’t know what to do to fix that. Any suggestions?
Thank you very much in advance.

Hi @zephyro,
As mentioned in this anouncement, Mbed TLS is now maintained under open governance at TrustedFirmware.org.
I would suggest you post your question there, as it doesn’t seem your question is Pelion related.

Your issue seems to be some platform related issue.
Could it be that the memory in segment A uses physical memory, and in segment B uses virtual memory?
Could it be a caching issue?
Regards,
Mbed Support
Ron

How about you do a mbedtls_sha256_init() before starting? Yea and don’t forget the mbedtls_sha256_free() if you’re really done.

You can test if the library works on your platform by calling the generic function mbedtls_sha256_ret().

int ret = 0;
char* data = “123456789”;
uint8_t hash[32];
mbedtls_sha256_context ctx;

ret = mbedtls_sha256_ret( data, stringlen(data), hash, 0 );