Python中的RSA加密无法在Java中解密
我使用私钥在 python 中进行 RSA 加密,并且无法使用公钥在 Java 中解密。下面是Python/Java源代码和异常。 我尝试了 PKCS1_OAEP 和哈希算法的多种组合,但得到了相同的错误。
同时,在同一平台内加密/解密工作正常(例如,使用公钥在 Java 或 Python 中加密并使用私钥解密,反之亦然,使用私钥在 Java 或 Python 中加密并使用公钥解密)
Java版本=1.8, Python 版本 = 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");
Java 中的异常
org.bouncycastle.jcajce.provider.util.BadBlockException: unable to decrypt block
Caused by: org.bouncycastle.crypto.InvalidCipherTextException: block incorrect
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论