使用私钥进行Python解密 [英] Python Decryption using private key
本文介绍了使用私钥进行Python解密的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个加密的字符串。加密是使用Java代码完成的。我使用以下Java代码解密加密的字符串
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;
}
现在我必须使用Python解密加密的字符串。我有私钥。当我使用以下代码使用密码封装
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())
它抛出 ValueError:无法反序列化关键数据。
有人可以帮助我在这里丢失的内容吗?
Can anyone help what I am missing here?
推荐答案
I找出解决方案:
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>)
这是最基本的代码形式。我了解到的是,首先您必须获得RSA_key(私钥)。对我来说, RSA.importKey
负责一切。真的很简单。
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.
这篇关于使用私钥进行Python解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文