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

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

How to fix it

  1. 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. 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

Related errors

Browse the full signature error database