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
EC private key in SEC 1 form
common`openssl ecparam -genkey` and many older tools write `EC PRIVATE KEY`. The crate's EC loader expects PKCS#8.
Loader of another key family
commonAn EC key passed to `from_rsa_pem`, an RSA key to `from_ec_pem`, or an Ed25519 key to either. Pick the loader by the key's algorithm.
Not a PEM at all
occasionalA JWK JSON string, a DER file, a certificate where a key is expected, or a PEM with escaped `\n` from configuration.
How to fix it
- 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.
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