我有一个加密的字符串。加密是使用java代码完成的。我使用以下java代码解密加密的字符串
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来解密加密的字符串。我有私钥。当我使用以下代码使用加密包时
key = load_pem_private_key(keydata, password=None, backend=default_backend())
它抛出ValueError:无法反序列化关键数据。
任何人都可以帮助我在这里缺少什么吗?
最佳答案
我找到了解决方案:
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
处理了一切。真的很简单。
关于Python 使用私钥解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39131630/