Skip to content
ecdsa.com
jsonwebtoken (Rust crate)Rust

Error message

Error(InvalidKeyFormat)

Also printed as

  • called `Result::unwrap()` on an `Err` value: Error(InvalidKeyFormat)
  • InvalidKeyFormat

`{:?}` prints `Error(InvalidKeyFormat)`, `{}` prints `InvalidKeyFormat`.

jsonwebtoken (Rust crate) — ErrorKind::InvalidKeyFormat from EncodingKey::from_ec_pem / DecodingKey::from_*_pem

What it means

The PEM you passed to an `EncodingKey`/`DecodingKey` constructor is not the structure that constructor accepts. For EC private keys `from_ec_pem` requires PKCS#8 (`-----BEGIN PRIVATE KEY-----`) and rejects the SEC 1 form (`-----BEGIN EC PRIVATE KEY-----`) that `openssl ecparam -genkey` writes; the RSA, EC and Ed25519 loaders each reject the other families' keys as well.

Why it happens

How to fix it

  1. 1.

    Convert the private key to PKCS#8

    One OpenSSL command converts SEC 1 or PKCS#1 private keys to PKCS#8, which every modern library reads.

    bash
    # SEC 1 ("EC PRIVATE KEY") or PKCS#1 ("RSA PRIVATE KEY") -> PKCS#8 ("PRIVATE KEY")
    openssl pkcs8 -topk8 -nocrypt -in ec-sec1.pem -out ec-pkcs8.pem
  2. 2.

    Use the loader that matches the key

    Each algorithm family has its own constructor; for JWKs use `DecodingKey::from_jwk`.

    rust
    let encoding = EncodingKey::from_ec_pem(&std::fs::read("ec-pkcs8.pem")?)?;   // ES256/ES384
    let decoding = DecodingKey::from_ec_pem(&std::fs::read("ec-public.pem")?)?;   // "PUBLIC KEY"
    let rsa = DecodingKey::from_rsa_pem(&std::fs::read("rsa-public.pem")?)?;     // RS*/PS*
    let ed = DecodingKey::from_ed_pem(&std::fs::read("ed25519-public.pem")?)?;   // EdDSA

Related errors

Browse the full signature error database