Error message
KeyRejected("InvalidEncoding")
Also printed as
- KeyRejected("WrongAlgorithm")
- called `Result::unwrap()` on an `Err` value: KeyRejected("InvalidEncoding")
The reason string varies: `InvalidEncoding`, `WrongAlgorithm`, `InconsistentComponents`, `TooSmall`… `Display` prints only the reason, e.g. `InvalidEncoding`.
ring (Rust crate) — ring::error::KeyRejected from EcdsaKeyPair::from_pkcs8 / Ed25519KeyPair::from_pkcs8
What it means
ring refused the private-key bytes. ring accepts exactly one encoding per key type — DER-encoded PKCS#8 (v1 or v2) for ECDSA and Ed25519, and for RSA also PKCS#1 DER via `from_der` — and reports only a short reason: `InvalidEncoding` when the bytes are not that structure, `WrongAlgorithm` when they are a valid PKCS#8 document for another algorithm or curve. ring never parses PEM itself.
Why it happens
PEM text passed as bytes
common`include_bytes!("key.pem")` or `fs::read("key.pem")` gives the PEM text. ring needs the base64-decoded DER inside it.
SEC 1 or PKCS#1 instead of PKCS#8
common`EC PRIVATE KEY` and `RSA PRIVATE KEY` files are other structures. ECDSA and Ed25519 key pairs in ring load only PKCS#8.
A key of another algorithm or curve
occasionalA P-384 key loaded with the P-256 signing algorithm, or an ECDSA key given to `Ed25519KeyPair`, yields `WrongAlgorithm`.
How to fix it
- 1.
Decode the PEM and check its label
Use a PEM parser, insist on the `PRIVATE KEY` label, and pass the decoded contents to ring.
rust // Cargo.toml: pem = "3" let pem = pem::parse(std::fs::read_to_string("key.pem")?)?; anyhow::ensure!(pem.tag() == "PRIVATE KEY", "expected PKCS#8, got {}", pem.tag()); let key_pair = EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_FIXED_SIGNING, pem.contents(), &rng) .map_err(|e| anyhow::anyhow!("key rejected: {e}"))?; - 2.
Convert legacy key files to PKCS#8 DER
OpenSSL converts SEC 1 and PKCS#1 private keys to PKCS#8; `-outform DER` writes exactly the bytes ring expects.
bash openssl pkcs8 -topk8 -nocrypt -in ec-sec1.pem -outform DER -out key.pk8 # SEC 1 -> PKCS#8 DER