2016-08-24 157 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照顧好了一切。真的很簡單。

相關問題