python-jose icon indicating copy to clipboard operation
python-jose copied to clipboard

jwk.construct() Unable to parse an RSA_JWK from _RSAPrivateKey object

Open DataGhost opened this issue 2 years ago • 0 comments

This is probably related to #50 but I'm not using a dict to construct my JWK, rather an instantiated private key. Also looking at the code I get the idea that #50 has been fixed long ago.

I cannot call jwk.construct with an already-instantiated private key (_RSAPrivateKey object). The error thrown is: jose.exceptions.JWKError: Unable to parse an RSA_JWK from key: <cryptography.hazmat.backends.openssl.rsa._RSAPrivateKey object at 0x7f6c480a4e20> I've loaded it using cryptography.hazmat.primitives.serialization.load_pem_private_key. The current constructor in python-jose seems to check for public keys only, which are directly assigned into self.prepared_key. My current workaround is serializing the _RSAPrivateKey object back into PEM/pkcs8 and calling jwk.construct on the resulting string, after which it does a call to load_pem_private_key anyway https://github.com/mpdavis/python-jose/blob/a374301d282a062bdb4c4ae399b215e9c4a62e49/jose/backends/cryptography_backend.py#L267 to get an identical result, the resulting jwkinstance.prepared_key is again an _RSAPrivateKey object. To me it seems an easy fix, just assign it similarly to: https://github.com/mpdavis/python-jose/blob/a374301d282a062bdb4c4ae399b215e9c4a62e49/jose/backends/cryptography_backend.py#L247-L249 after checking that it conforms to the private key interface.

My use case is having an encrypted private key so I need to decrypt it before constructing the JWK, as there is no way for me to pass the password into the constructor and letting it handle that. Reserialization seems like an unnecessary extra step.

DataGhost avatar Nov 24 '21 13:11 DataGhost