python-jose
python-jose copied to clipboard
Add a clear example to readme on how to generate a pair of keys acceptable to python-jose
I took a shot and I failed. Now I will have to spend a while figuring out exactly what Python Jose prefers. A readme would take out the guesswork and make a statement as to the best practice.
ssh-keygen -t rsa -b 2048 -f jwtRS256.key
openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub
cat jwtRS256.key
cat jwtRS256.key.pub
<copy the private key into a python script>
>>> import jose.jwt
>>> PRIVATE_KEY = '<big long thing>'
>>> token = jose.jwt.encode({'a': 'b'}, PRIVATE_KEY, algorithm='RS256')
<snip>
jose.exceptions.JWSError: RSA key format is not supported
For anyone else stumbling across this (in particular if you get the above error or the even-less-scrutable jose.exceptions.JWSError: list index out of range), the RSA private key needs to have \n literals instead of spaces or removing line breaks entirely (assuming you don't want to have a multiline string with your private key in your code).
E.g. (obviously this will not actually run, since the RSA key is not valid):
$ cat example_rsa
-----BEGIN RSA PRIVATE KEY-----
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc
-----END RSA PRIVATE KEY-----
$
$ sed -E ':a;N;$!ba;s/\n/\\n/g' example_rsa
-----BEGIN RSA PRIVATE KEY-----\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\n-----END RSA PRIVATE KEY-----
$ python
>>> from jose import jwt
>>> token = jwt.encode({'a': 'b'}, '-----BEGIN RSA PRIVATE KEY-----\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\ncccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\n-----END RSA PRIVATE KEY-----', algorithm='RS256')
>>> token
ddd.eee.fff
sigh