Mbed-TLS / mbedtls

An open source, portable, easy to use, readable and flexible TLS library, and reference implementation of the PSA Cryptography API. Releases are on a varying cadence, typically around 3 - 6 months between releases.
https://www.trustedfirmware.org/projects/mbed-tls/
Other
5.02k stars 2.5k forks source link

Function to calculate certificate fingerprint #9187

Open gustavowd opened 1 month ago

gustavowd commented 1 month ago

Suggested enhancement

In mbedtls I found a function to calculate the certificate sha256 checksum and message digest from SHA1, SHA256, etc. However, I can't found any function to calulate the certificate fingerprint.

The mbedtls function mbedtls_sha256() or mbedtls_md() with MBEDTLS_MD_SHA256 argument return the same result, which is equivalent to the sha256sum command on linux bash. However, what I need is the fingerprint that I can obtain from such command: openssl x509 -noout -fingerprint -sha256 -in certificate.pem

Justification

There are some IoT protocols that uses the certificate fingerprint to set a device identifier.

Mbed TLS needs this because I believe that mbedtls is the right choice to implement such function for embedded systems.

davidhorstmann-arm commented 3 weeks ago

Hi,

The SHA256 fingerprint as generated by OpenSSL is just the SHA256 hash of the DER-encoded certificate. You should be able to compute this by parsing the certificate and then hashing the raw.p field (which contains the raw DER-encoded content). This would look something like the following code:

ret = psa_crypto_init();
/* Deal with errors etc */
...
ret = mbedtls_x509_crt_parse_file(&crt, "certificate.pem");
/* Deal with errors etc */
...
ret = psa_hash_compute(PSA_ALG_SHA_256,
                       crt.raw.p, crt.raw.len,
                       output_buffer, output_buffer_length,
                       &hash_length);
/* Deal with errors etc */

/* output_buffer now contains the calculated fingerprint */

I've shown an example using the newer PSA crypto API, as the legacy mbedtls_sha256_...() API will be removed in Mbed TLS 4.0. For more examples of hashing this way see the hashing example program.