使用私钥的Python解密

2024-09-29 22:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个加密的字符串。加密是使用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: Could not unserialize key data.

有人能帮我吗?


Tags: key字符串代码stringexceptionbyteprivateout
1条回答
网友
1楼 · 发布于 2024-09-29 22:24:49

我想出了解决办法:

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_密钥(私钥)。对我来说,RSA.importKey照顾好了一切。很简单。

相关问题 更多 >

    热门问题