0

I have generated an ssh key with:

ssh-keygen -t rsa -b 4096

Resulting in this:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

Now trying to generate a jwt with this key:

import jwt

key = open("~/.ssh/id_rsa", "r").read()
token = jwt.encode(
    claim={'iss': 'me'},
    key=key,
    algorithm='RS256'
)

I got the error:

ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=503841036, lib=60, reason=524556, reason_text=b'error:1E08010C:DECODER routines::unsupported')])

Is it not possible to use openSSH key to sign the data?

renatodamas
  • 16,555
  • 8
  • 30
  • 51
  • does [this](https://stackoverflow.com/questions/54994641/openssh-private-key-to-rsa-private-key) help? – jps Nov 01 '22 at 18:53

1 Answers1

1

PyJWT requires the Cryprography library for RSA, see here. Cryptography in turn supports the OpenSSH format, see here and here, e.g.:

import jwt
from cryptography.hazmat.primitives import serialization

private_key_OpenSSH = b'''-----BEGIN OPENSSH PRIVATE KEY-----
b3Blbn....suThWLDRnmD
-----END OPENSSH PRIVATE KEY-----'''

private_key = serialization.load_ssh_private_key(private_key_OpenSSH, password=None) 
encoded = jwt.encode({"some": "payload"}, private_key, algorithm="RS256")
...

If the key is secured with a password, additionally the bcrypt module must be installed.

Topaco
  • 40,594
  • 4
  • 35
  • 62