使用私钥的Python解密
我有一个加密字符串。加密是使用java代码完成的。我使用以下java代码解密加密的字符串使用私钥的Python解密,python,cryptography,Python,Cryptography,我有一个加密字符串。加密是使用java代码完成的。我使用以下java代码解密加密的字符串 InputStream fileInputStream = getClass().getResourceAsStream( "/private.txt"); byte[] bytes = IOUtils.toByteArray(fileInputStream); private String decrypt(String inputStr
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>)
从Crypto.PublicKey导入RSA
从加密签名导入PKCS1\u v1\u 5
从base64导入B64解码
rsa_key=rsa.importKey(open('private.txt',“rb”).read())
cipher=PKCS1\u v1\u 5.新(rsa\u密钥)
原始密码数据=B64解码()
phn=cipher.decrypt(原始密码数据)
这是最基本的代码形式。我学到的是,首先必须获得RSA_密钥(私钥)。对我来说,RSA.importKey负责一切。非常简单。永远不要使用RSA。不使用填充或使用不好的填充是非常不安全的。现在,您应该使用OAEP而不是默认的PKCS#1 v1.5填充。因此,您可能应该使用Cipher.getInstance(“RSA/ECB/OAEPWithSHA-256和mgf1padding”)应该是来自Crypto.Cipher import PKCS1\u v1\u 5的
吗?是什么?请你详细说明一下好吗