Dutta Dutta - 10 months ago 123
Python Question

Python Decryption using private key

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(
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());
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) {
.println("Exception while using the cypher::::::::::::::::: "
+ e.getMessage());
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?


I figured out the solution:

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

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

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.