[Python] I am unable to load ed25519 private key in PEM format in Python

Discussão em 'Python' iniciado por Stack, Março 21, 2025.

  1. Stack

    Stack Membro Participativo

    I ripped code straight off of the jwt documentation website as I try to implement JWT. Their example works fine. However, when I try it with an ssh-keygen file, in PKCS8 format, it doesn't work:

    import jwt
    private_key = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPtUxyxlhjOWetjIYmc98dmB2GxpeaMPP64qBhZmG13r\n-----END PRIVATE KEY-----\n"
    public_key = "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEA7p4c1IU6aA65FWn6YZ+Bya5dRbfd4P6d4a6H0u9+gCg=\n-----END PUBLIC KEY-----\n"
    encoded = jwt.encode({"some": "payload"}, private_key, algorithm="EdDSA")
    jwt.decode(encoded, public_key, algorithms=["EdDSA"])
    print("pass")

    with open("id_ed25519", "r") as f:
    private_key = f.read()
    print(private_key)

    with open("id_ed25519.pub", "r") as f:
    public_key = f.read()
    print(public_key)

    encoded = jwt.encode({"some": "payload"}, private_key, algorithm="EdDSA")
    jwt.decode(encoded, public_key, algorithms=["EdDSA"])
    print("it works!")


    produces:

    pass
    -----BEGIN OPENSSH PRIVATE KEY-----
    b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAMwAAAAtzc2gtZW
    QyNTUxOQAAACCx/iwn0j++zhjIzFYUYzQEIUUS9LJuAOPUPIsjAvi6HQAAAJgS8hOAEvIT
    gAAAAAtzc2gtZWQyNTUxOQAAACCx/iwn0j++zhjIzFYUYzQEIUUS9LJuAOPUPIsjAvi6HQ
    AAAEAT87A79bj9AFXc0iAgBKPnDoxGE6wcxZMVRgnfnGaoJbH+LCfSP77OGMjMVhRjNAQh
    RRL0sm4A49Q8iyMC+LodAAAAFWNib25naW9yQGNib25naW9yLW1hYw==
    -----END OPENSSH PRIVATE KEY-----

    ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAILH+LCfSP77OGMjMVhRjNAQhRRL0sm4A49Q8iyMC+Lod
    raise InvalidKeyError(
    jwt.exceptions.InvalidKeyError: Expecting a EllipticCurvePrivateKey/EllipticCurvePublicKey. Wrong key provided for EdDSA algorithms


    Here are some details about the keys in question:

    echo -n "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIPtUxyxlhjOWetjIYmc98dmB2GxpeaMPP64qBhZmG13r\n-----END PRIVATE KEY-----\n" > testme
    -> % ssh-keygen -l -f testme
    256 SHA256:ZSZKe1nlMIpu8Jjivb/0nmN6xZrXVreNs2P4uX4jvlk no comment (ED25519)
    -> % ssh-keygen -t ed25519 -p -m "PKCS8"
    -> % ssh-keygen -l -f id_ed25519
    256 SHA256:M15wqcX0NGIYuRIeziO3WOEDxhfmyhqsD1O32I02VFc cbongior@cbongior-mac (ED25519)
    -> % wc -c testme
    119 testme
    (.venv) cbongior@cbongior-mac [14:20:48] [~/dev/oracle/fleetman] [main *]
    -> % wc -c id_ed25519
    411 id_ed25519


    Both files are valid, but the biggest difference is the size and (I assume) the encoding. The first one looks to be PKCS8 encoded (so, that's what I told ssh to generate the key as).

    I am not sure what the difference is, but clearly jwt doesn't like my ssh key. Can someone explain what the issue is? Obviously I am expecting it to print it works!

    Continue reading...

Compartilhe esta Página