Python Decryption using private key

17,562

I figured out the solution:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from base64 import b64decode

rsa_key = RSA.importKey(open('private.txt', "rb").read())
cipher = PKCS1_v1_5.new(rsa_key)
raw_cipher_data = b64decode(<your cipher data>)
phn = cipher.decrypt(raw_cipher_data, <some default>)

This is the most basic form of code. What I learned is first you have to get the RSA_key(private key). For me RSA.importKey took care of everything. Really simple.

Share:
17,562
Dutta
Author by

Dutta

Updated on June 04, 2022

Comments

  • Dutta
    Dutta almost 2 years

    I have an encrypted string. The Encryption is done using java code. I decrypt the encrypted string using following java code

    InputStream fileInputStream = getClass().getResourceAsStream(
                        "/private.txt");
                byte[] bytes = IOUtils.toByteArray(fileInputStream);
    
    
    
    private String decrypt(String inputString, byte[] keyBytes) {
            String resultStr = null;
            PrivateKey privateKey = null;
            try {
                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(keyBytes);
                privateKey = keyFactory.generatePrivate(privateKeySpec);
            } catch (Exception e) {
                System.out.println("Exception privateKey:::::::::::::::::  "
                        + e.getMessage());
                e.printStackTrace();
            }
            byte[] decodedBytes = null;
            try {
                Cipher c = Cipher.getInstance("RSA/ECB/NoPadding");
                c.init(Cipher.DECRYPT_MODE, privateKey);
                decodedBytes = c.doFinal(Base64.decodeBase64(inputString));
    
            } catch (Exception e) {
                System.out
                        .println("Exception while using the cypher:::::::::::::::::  "
                                + e.getMessage());
                e.printStackTrace();
            }
            if (decodedBytes != null) {
                resultStr = new String(decodedBytes);
                resultStr = resultStr.split("MNSadm")[0];
                // System.out.println("resultStr:::" + resultStr + ":::::");
                // resultStr = resultStr.replace(salt, "");
            }
            return resultStr;
    
        }
    

    Now I have to use Python to decrypt the encrypted string. I have the private key. When I use Cryptography package using following code

    key = load_pem_private_key(keydata, password=None, backend=default_backend())
    

    It throws ValueError: Could not unserialize key data.

    Can anyone help what I am missing here?

  • Charles L.
    Charles L. over 4 years
    Should it be from Crypto.Cipher import PKCS1_v1_5 instead?
  • Sunny Chaudhari
    Sunny Chaudhari over 3 years
    what is <some default> ? Please can you elaborate