Reputation: 12585
I have the following JSON object which represents an RSA256 JWK which obtained from a website:
jwk = {
'e': 'AQAB',
'n': 'sAlE_mzYz-2jf_YpxulSJXv_2CGIquflNZWhXUaU1SkJm9P0riLAuzwK7WT5p0Ko3zmQHho70_7D9nqB01rA4ExrMIDKpprE0Qa7NAJN-kgZhd_A25HsdSfpOfpaLvR-mf9fuOTDPLRQCd5HnrjoQKjs3D_XfPmPnT_Ny5erviiky90GSfN9j2DP_5yeDprzWKF-EQ3EDdIWt3snr7AW8rzBcZ1ojyWxckLAeSKDerMXP-zVBUFJE9Kn60HZoGNvmATKaw8LwEbf8DGfrllgSLvhg7mDRMLlbcooQoWAFSfN7t7kFbPSOcvjrpx3Yw_KrEwBZXeUP3260ukmFOx8RQ',
}
Below is the Perl code showing how a public-key object from the Crypt library can be constructed from the above jwk:
use Crypt::OpenSSL::RSA;
use Crypt::OpenSSL::Bignum;
use MIME::Base64 qw/decode_base64url/;
sub public_key {
my $rsa = Crypt::OpenSSL::RSA->new_key_from_parameters(
Crypt::OpenSSL::Bignum->new_from_bin(decode_base64url($jwk->{n})),
Crypt::OpenSSL::Bignum->new_from_bin(decode_base64url($jwk->{e})),
);
return $rsa->get_public_key_x509_string;
}
Two Questions:
How can I translate the above code into Python? The code below failed.
Once I have the public key object in python, how can I use it to verify a JWT signed by the corresponding private key? Please post a snippet showing exactly how it can be done.
>>> from Crypto.PublicKey import RSA
>>> import base64
>>> public_key = RSA.construct((base64.b64decode(jwk['n']), base64.b64decode(jwk['e'])))
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my-virtual-env/lib/python2.7/site-packages/Crypto/PublicKey/RSA.py", line 539, in construct
key = self._math.rsa_construct(*tup)
File "my-virtual-env/lib/python2.7/site-packages/Crypto/PublicKey/_slowmath.py", line 84, in rsa_construct
assert isinstance(n, long)
AssertionError
Upvotes: 2
Views: 305
Reputation: 3176
The error is raised because the RSA contructor is expecting 2 long integers and you are using two strings.
The solution is to convert the base64 decoded string into an hexadecimal integer.
from Crypto.PublicKey import RSA
import base64
n = int(base64.b64decode(jwk['n']).encode('hex'),16)
e = int(base64.b64decode(jwk['e']).encode('hex'),16)
e = long(e)
public_key = RSA.construct((n, e))
print(public_key)
Regarding the second question maybe you can use this method to verify the validity of an RSA signature.
Upvotes: 2