Mbedtls context initilization scope issue

I am seeing the issue especially for type mbedtls_pk_context.

sample1:
void foo()
{

    re = mbedtls_pk_parse_public_key(&ctx,key,keyLen);
    if(re)
    {
        LOG( "parse_public_keyfile -0x%04x\n", -ret );
        return re;
    }
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The above code works fine.

However, If I move the mbedtls_pk_context ctx in global and decouple the init and operation function as shown below in Sample2, ctx somehow is NULL or contain some junk. mbedtls_pk_setup returns MBEDTLS_ERR_PK_BAD_INPUT_DATA.

Sample2:

mbedtls_pk_context ctx;
void init()
{
     mbedtls_pk_init(&ctx);
}
void operations()
{        
    mbedtls_pk_init(&ctx);
    re = mbedtls_pk_parse_public_key(&ctx,key,keyLen);
    if(re)
    {
        LOG( "parse_public_keyfile -0x%04x\n", -ret );
        return re;
    }
}

Hi @gopi219
In your Sample2 code, you are also calling mbedtls_pk_init() in your operations() code, but I am assuming this is a writer’s error, according to your description.
As you can see from the code, mbedtls_pk_init() sets all the internals of the context to NULL, for further operations, but if you are saying that ctx is NULL or garbagem I believe this is something related to the memory layout of your platform.
Are you working on a multi threaded environment? Is your ctx protected by a mutex? Is it possible that the operations() is called before init() function ? Does the behavior change when you set your ctx to a static member that only the translation unit would identify?
regards,
Mbed TLS Team member
Ron

It is multi threaded environment; but init() and operation() is called from single thread. And also, init() is called before(only once) operation() function is called multiple times, while there is need for changing the public key. A public key is valid for 24 Hrs; similarly, I tried to reuse the existing context with different public key. Is that right approach?

In understood the issue, If I have to use new Public key, I must create new context, Same context couldn’t be re-used or at least it must be re-initialized.

Thanks :slight_smile:

Yes,
If your context already have information from previous key, then it might not have the information you think it has, when you parse new key.
re initializing is the right approach ( better freeing it before re-initializing )