Search code examples
pythonjavarsapublic-key-encryptionpublic-key

Java to Python - Pass RSA Public Key into Function


I am trying to convert an encryption algorithm that uses RSA Encryption from Java to Python.

I have been working on it for a week and have made some progress but I have stuck on converting this Java specific function below.

    private static String encryptMessage(String randomToken, PublicKey publicKey) throws Exception {
    Cipher cipher = Cipher.getInstance("RSA");
    cipher.init(Cipher.ENCRYPT_MODE, publicKey);
    return Base64.encodeBase64String(cipher.doFinal(randomToken.getBytes()));
}

I am trying to figure out how to pass the public key which is in this format in Java into a python data type to be passed into the function.

{public=Sun RSA public key, 2048 bits
  params: null
  modulus: 5438....
  public exponent:12237}

Once I am able to pass the key in the correct format. What are the python equivalent calls within the function?

Some assistance and Guidance would be very much helpful.


Solution

  • Using the pycryptodome library I was able to construct the correct public key using the modulus and exponent.

    https://pycryptodome.readthedocs.io/en/latest/src/public_key/rsa.html#Crypto.PublicKey.RSA.construct