2016-08-24 153 views
-1

我有一个加密的字符串。加密使用java代码完成。我使用下面的Java代码使用私钥解密Python

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.

谁能帮助我是缺少在这里?

+0

永远不要使用教科书RSA。使用没有填充或不好的填充是非常不安全的。现在,您应该使用OAEP而不是默认的PKCS#1 v1.5填充。所以你应该使用'Cipher.getInstance(“RSA/ECB/OAEPWithSHA-256AndMGF1Padding”);' –

回答

2

我想出了解决方案:

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

相关问题