On 11/20/2023 4:56 AM, Gilles Peskine wrote:
Hi Christian,
We are planning to add a pk-like parsing interface to PSA. See https://github.com/ARM-software/psa-api/issues/44 and https://github.com/Mbed-TLS/mbedtls/pull/7910.
I added my own parser for now. I will replace it when version 4.0 is ready.
Unfortunately, due to resource constraints, this API will not be available until Mbed TLS 4.0 (if not 4.1). In the meantime, when Mbed TLS is built with MBEDTLS_USE_PSA_CRYPTO, you can use mbedtls_pk_parse_key and friends to parse a key, then construct a PSA key from that. See https://github.com/Mbed-TLS/mbedtls/pull/7766 for some tips in transitioning from the legacy crypto API to PSA, with code fragments. This is somewhat cumbersome, and we do plan to improve the situation in Mbed TLS 3.6 by providing better bridges between PK and PSA. We haven't yet finalized the design there, so please feel free to open a feature request on GitHub if there isn't already an issue that covers your use case.
But of course our use case includes EC keys!
By the way, the reason this happens to work with RSA keys, but not with EC keys, is that PSA uses the smallest sensible input format. For RSA keys, there are multiple numbers to encode and the smallest sensible format is an ASN.1 format that is “high-level” enough for pkparse. PSA does not support PEM imports, but this just happens to work because the PSA code calls a lower-level function that also tries to parse PEM. With EC keys, the smallest sensible format is just the private value (for private keys) or a compact encoding of the two coordinates (for public keys), and this doesn't contain enough metadata for pkparse to support it.
I wrote a parser that reuses mbedtls_pk_load_file to the base64 PEM input and get material in three formats -- RSA key, EC key, and "public key". For public key format, I wrote a few lines of DER/ASN1 code to parse the OID and recognize RSA, EC and ED25519. For RSA, this gives me the same input as that of "RSA key", which I can feed into psa_import_key. For EC, I need a bit more DER parsing to get to the actual private key and use psa_import_key. Once the "attributes" are set correctly, it works.
For ED25519, I did the parsing and retrieved the private key, but I cannot successfully import it. Reading the status of various PRs, I am not sure whether ED25519PH is actually supported. Or maybe I am doing it wrong and not setting the attributes correctly. I could really use a sample for that!
-- Christian Huitema