I am trying to sign a JSON encoded object with jws.sign and hence tried this example given here: https://python-jose.readthedocs.io/en/latest/jws/index.html
But problem is that jws.sign is working fine with algorithm HS256 given in the example above but fails with algorithm RS256 with this error:
signed = jws.sign({'a': 'b'}, 'secret', algorithm='RS256') Traceback (most recent call last): File "/usr/local/lib/python3.7/dist-packages/jose/backends/cryptography_backend.py", line 231, in init self.prepared_key = load_pem_public_key(key, self.cryptography_backend()) File "/usr/local/lib/python3.7/dist-packages/cryptography/hazmat/primitives/serialization/base.py", line 23, in load_pem_public_key return backend.load_pem_public_key(data) File "/usr/local/lib/python3.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 1273, in load_pem_public_key self._handle_key_loading_error() File "/usr/local/lib/python3.7/dist-packages/cryptography/hazmat/backends/openssl/backend.py", line 1526, in _handle_key_loading_error raise ValueError("Could not deserialize key data.") ValueError: Could not deserialize key data.
Any leads will be helpful
I was in the same situation as you were, for several days, after a lot of searching I finally understood what the problem was and I came up with the solution below. Let me explain.
Issues
The 'secret' used as a key is applicable for HS256 algorithm, however, it is not applicable for RS256 algorithm.
Improvements needed
Go to a RSA Key Generator website such as: https://cryptotools.net/rsagen and generate a key. (Retain default settings on the website.)
Copy the Private and Public Keys into separate variables in your code. We need the Public Key to verify.
Note: Retain the newlines AFTER
-----BEGIN RSA PRIVATE KEY-----
and BEFORE-----END RSA PRIVATE KEY-----
. They are a must, if you miss them then you will again get the deserialize error.Output: