Python使用私钥解密

时间:2016-08-24 19:31:14

标签: python cryptography

我有一个加密的字符串。加密是使用java代码完成的。我使用以下java代码解密加密的字符串

<?php foreach ($things as $thing): ?>
  <li><?php echo $thing; ?></li>
<?php endforeach; ?>

现在我必须使用Python来解密加密的字符串。我有私钥。当我使用以下代码使用Cryptography包时

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;

    }

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

任何人都可以帮助我在这里失踪吗?

1 个答案:

答案 0 :(得分:3)

我找到了解决方案:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
from base64 import b64decode

rsa_key = RSA.importKey(open('private.txt', "rb").read())
verifier = PKCS1_v1_5.new(rsa_key)
raw_cipher_data = b64decode(<your cipher data>)
phn = rsa_key.decrypt(raw_cipher_data)

这是最基本的代码形式。我学到的是首先你需要获得RSA_key(私钥)。对我来说RSA.importKey照顾好一切。真的很简单。