benmcollins / libjwt

JWT C Library
Mozilla Public License 2.0
349 stars 164 forks source link

finalize mbedTLS support #192

Open xback opened 7 months ago

xback commented 7 months ago

Hi @benmcollins

I'm rewriting our internal application to add mbedTLS support next to openssl in order to reduce memory load. libjwt is the final piece remaining ..

I noticed in another thread that you've already played around with it and support was nearly finished. Could you share this work so I can finalize it? (separate branch or so?)

Thanks again!

benmcollins commented 7 months ago

Hello,

Yes, I did work on mbedTLS support for LibJWT for a private customer. However, it was an embedded product, and the support only covered creating RSA256 tokens, so it was very very limited.

What I have here is one function needed for the mbedTLS support. This is not a drop-in replacement, but it should get you started in creating a jwt-mbedtls.c file to support the functionality in LibJWT:

int jwt_sign_sha_pem(char **out, unsigned int *len, const char *str)
{
    int ret = -1;
    mbedtls_pk_context pk;
    mbedtls_entropy_context entropy;
    mbedtls_ctr_drbg_context ctr_drbg;
    unsigned char hash[32];
    const char *pers = "mbedtls_jwt";
    size_t olen = 0;
    static unsigned char sig[MBEDTLS_MPI_MAX_SIZE];

    /* Initialize the mbedTLS modules we need. */
    mbedtls_entropy_init(&entropy);
    mbedtls_ctr_drbg_init(&ctr_drbg);
    mbedtls_pk_init(&pk);

    /* Initialize the seed. */
    if (mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy,
                              (const unsigned char *) pers, strlen(pers)))
            goto sign_error;

    /* Parse the PEM formatted key (could be DER as well). */
    if (mbedtls_pk_parse_key(&pk, jwt_key, jwt_key_len + 1, NULL, 0))
            goto sign_error;

    /* Get the SHA256 Hash. */
    if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
                   (const unsigned char *)str, strlen(str), hash))
            goto sign_error;

    /* Sign and get the output. */
    if (mbedtls_pk_sign(&pk, MBEDTLS_MD_SHA256, hash, 0, sig, &olen,
                        mbedtls_ctr_drbg_random, &ctr_drbg))
            goto sign_error;

    ret = 0;
    *out = (char *)sig;
    *len = olen;

sign_error:
    mbedtls_entropy_free(&entropy);
    mbedtls_ctr_drbg_free(&ctr_drbg);
    mbedtls_pk_free(&pk);

    return ret;
}
xback commented 7 months ago

Great! Thanks a lot for the fast reply