Dut*_*tta 2 python cryptography
我有一个加密的字符串。加密是使用 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;
}
Run Code Online (Sandbox Code Playgroud)
现在我必须使用 Python 来解密加密的字符串。我有私钥。当我使用以下代码使用加密包时
key = load_pem_private_key(keydata, password=None, backend=default_backend())
Run Code Online (Sandbox Code Playgroud)
它抛出 ValueError: Could not unserialize key data.
任何人都可以帮助我在这里缺少的东西吗?
我想出了解决方案:
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>)
Run Code Online (Sandbox Code Playgroud)
这是最基本的代码形式。我学到的是首先你必须得到 RSA_key(私钥)。为我RSA.importKey照顾一切。真的很简单。