Python 使用私钥解密

标签 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;

    }

现在我必须使用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/

相关文章:

c++ - C++ 中大型模的模幂运算失败

Python:私有(private)内部枚举类中的静态方法

python - 使用 Numpy.genfromtxt 上传多种格式的数据

go - 使用此代码您如何知道是否会使用 sha256 或 sha512?

Android jar 使用有效的 keystore 未签名,需要 SHA1 证书吗?

iis - 使用 IISWASOnlyAesProvider 生成加密的 IIS 应用程序池标识密码

filesystems - 文件的 MD5 哈希在每个系统上都是唯一的吗?

python - 访问在不同模块中创建的对象

python - asyncio - 如何在信号处理程序中使用协程?

python - 指定图例框的线宽,matplotlib中