1 year ago
#374763
Mikhail.Mamaev
RSA encryption in Python unable to decrypt in Java
I make RSA encryption in python with private key and cannot decrypt in Java with public key. Below is Python/Java source codes and exception. I tried multiple combinations with PKCS1_OAEP and hash algorythms but getting the same error.
At the same time encription / decription within the same platform works fine (e.g. encrypt in Java or Python with public key and decrypt with private and vice versa encrypt in Java or Python with private key and decrypt with public)
Java version = 1.8, Python version = 3.10
Python
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
KEY = "-----BEGIN RSA PRIVATE KEY-----\n" \
"MII...WI=" \
"\n-----END RSA PRIVATE KEY-----"
#import private key
priv_key = RSA.import_key(KEY)
rsa_cipher = PKCS1_v1_5.new(priv_key)
#encode text
enc_text = rsa_cipher.encrypt("Hello Stackoverflow".encode('utf-8'))
enc_text_64 = base64.b64encode(cipher_text).decode("utf-8")
print(enc_text_64)
Java
PublicKey pubKey = CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decodeBase64(PUBLIC_KEY))).getPublicKey();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", new BouncyCastleProvider());
cipher.init(Cipher.DECRYPT_MODE, pubKey);
String res = new String(cipher.doFinal(Base64.getMimeDecoder().decode(str)), "utf-8");
Exception in Java
org.bouncycastle.jcajce.provider.util.BadBlockException: unable to decrypt block
Caused by: org.bouncycastle.crypto.InvalidCipherTextException: block incorrect
python
java
encryption
rsa
pkcs#1
0 Answers
Your Answer