0

I know that there are answers already on SO, but after trying a few of them (ex1, ex2) I still cannot produce the correct public key from modulus and an exponent.

This is my python3 code:

from Crypto.PublicKey.RSA import construct
import urllib.parse
import base64
import re

def decode_base64(data, altchars=b'+/'):
    """Decode base64, padding being optional.

    :param data: Base64 data as an ASCII byte string
    :returns: The decoded byte string.

    """
    data = re.sub(rb'[^a-zA-Z0-9%s]+' % altchars, b'', data)  # normalize
    missing_padding = len(data) % 4
    if missing_padding:
        data += b'='* (4 - missing_padding)
    return base64.b64decode(data, altchars)

e = int.from_bytes(decode_base64(b'AQAB'), 'big', signed=False)
decoded = decode_base64(b'tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmLiWZizpb-h0qup5jznOvOr-Dhw9908584BSgC83YacjWNqEK3urxhyE2jWjwRm2N95WGgb5mzE5XmZIvkvyXnn7X8dvgFPF5QwIngGsDG8LyHuJWlaDhr_EPLMW4wHvH0zZCuRMARIJmmqiMy3VD4ftq4nS5s8vJL0pVSrkuNojtokp84AtkADCDU_BUhrc2sIgfnvZ03koCQRoZmWiHu86SuJZYkDFstVTVSR0hiXudFlfQ2rOhPlpObmku68lXw-7V-P7jwrQRFfQVXw', 'big')

n = int.from_bytes(decoded, 'big', signed=False)

rsaKey = construct((n, e))                                                                                      
pubKey = rsaKey.exportKey()                                                                                            
print(pubKey.decode('ascii'))

But whenever I try to verify a jwt token I get a "signature_invalid" error.

Am I not decoding the binary encoded bytes correctly?

----UPDATE--- As suggested in the comments, I've updated my code to url decode the bytes first, but I still get the same signature invalid error as before.

Copil tembel
  • 399
  • 4
  • 22
  • 1
    Your decoding is incorrect, first you must convert `b'AQAB'` and `b'tV...'` to bytes using a url-safe base64 decoder like `base64.urlsafe_b64decode`. Then convert the bytes to ints. – President James K. Polk Feb 09 '21 at 17:17
  • 1
    maybe [this](https://stackoverflow.com/questions/65920029/generate-a-public-key-with-a-predefined-modulus-and-exponent-strange-values) helps. It's asolution based on Python-Jose – jps Feb 09 '21 at 18:08
  • @jps: Awesome! This helps a lot. – Copil tembel Feb 09 '21 at 18:59
  • @Copiltembel glad to know it helped. Feel free to upvote the answer ;) – jps Feb 09 '21 at 20:15

0 Answers0