Skip to content
ecdsa.com
Python cryptographyPython cryptography

Error message

Unable to load PEM file. See https://cryptography.io/en/latest/faq/#why-can-t-i-import-my-pem-file for more details. MalformedFraming

The sentence before the token is fixed; the token names what went wrong. MalformedFraming means the BEGIN/END lines were not found; MismatchedTags("PRIVATE KEY", "PUBLIC KEY") means they do not match; InvalidData(Invalid symbol 92, offset 0.) means the body is not base64 — 92 is a backslash, the mark of literal \n sequences.

Python cryptography — ValueError from load_pem_* functions

What it means

load_pem_private_key / load_pem_public_key / load_pem_x509_certificate could not find intact PEM framing — matching BEGIN and END lines with a base64 body between them. The trailing token (MalformedFraming here) is the parser's diagnosis; the FAQ link ships inside the error text itself.

Why it happens

How to fix it

  1. 1.

    Normalize before loading

    Restore newlines, strip whitespace and quotes, and confirm the first line before handing bytes to the loader.

    python
    import os
    pem = os.environ["PRIVATE_KEY"].replace("\\n", "\n").strip().strip('"').encode()
    assert pem.startswith(b"-----BEGIN"), pem[:30]
    
    from cryptography.hazmat.primitives.serialization import load_pem_private_key
    key = load_pem_private_key(pem, password=None)
  2. 2.

    Prefer files or native multiline secrets

    Mounted secret files avoid the escaping problem entirely; Kubernetes Secrets and most vaults can deliver the PEM byte-exact.

    python
    with open("/run/secrets/signing_key.pem", "rb") as f:
        key = load_pem_private_key(f.read(), password=None)
  3. 3.

    Validate the framing mechanically

    A quick check that BEGIN/END lines exist and match narrows the fault to content vs transport.

    python
    lines = pem.decode().splitlines()
    print(lines[0])   # -----BEGIN PRIVATE KEY-----
    print(lines[-1])  # -----END PRIVATE KEY-----

Related errors

Browse the full signature error database