【问题标题】:Python Decryption using private key使用私钥的 Python 解密
【发布时间】:2016-08-24 19:31:13
【问题描述】:

我有一个加密字符串。加密是使用 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 来解密加密的字符串。我有私钥。当我使用以下代码使用 Cryptography 包时

key = load_pem_private_key(keydata, password=None, backend=default_backend())

它抛出ValueError: Could not unserialize key data.

谁能帮助我在这里缺少什么?

【问题讨论】:

  • 永远不要使用教科书 RSA。不使用填充或错误的填充是非常不安全的。现在,您应该使用 OAEP 而不是默认的 PKCS#1 v1.5 填充。所以你可能应该使用Cipher.getInstance("RSA/ECB/OAEPWithSHA-256AndMGF1Padding");

标签: python cryptography


【解决方案1】:

我想出了解决办法:

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 照顾了一切。真的很简单。

【讨论】:

  • 应该改成from Crypto.Cipher import PKCS1_v1_5吗?
  • 什么是 ?请你详细说明
猜你喜欢
  • 2022-10-20
  • 1970-01-01
  • 2017-07-07
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-27
相关资源
最近更新 更多