2017-05-09 186 views
1

我有一個包含私鑰和證書的.p7m格式的電子郵件附件和.pem文件。 使用OpenSSL的,我可以解密用這個命令文件:Java解密電子郵件附件(.p7m文件)

openssl smime -decrypt -inform DER -in fileToDecrypt.p7m -inkey privateKey.pem -out destinationFile 

但在Java中使用BouncyCastle的,我無法解密。 我讀到這段代碼的私有密鑰:

PEMReader pemReader = new PEMReader(new InputStreamReader(new FileInputStream(privateKeyName))); 
    Object obj; 
    PrivateKey key = null; 
    X509Certificate cert1 = null; 
    X509Certificate cert2 = null; 

    obj = pemReader.readObject(); 
    if (obj instanceof PrivateKey) { 
     key = (PrivateKey) obj; 
     System.out.println("Private Key found"); 
    } 
    obj = pemReader.readObject(); 
    if(obj instanceof X509Certificate){ 
     cert1 = (X509Certificate) obj; 
     System.out.println("cert found"); 
    } 
    obj = pemReader.readObject(); 
    if(obj instanceof X509Certificate){ 
     cert2 = (X509Certificate) obj; 
     System.out.println("cert found"); 
    } 

這會打印出:

Private Key Found 
cert found 
cert found 

類型的關鍵是:

System.out.println(key.getAlgorithm()); 
System.out.println(cert1.getSigAlgName()); 
System.out.println(cert2.getSigAlgName()); 

RSA 
SHA256WithRSAEncryption 
SHA256WithRSAEncryption 

如果我嘗試解密這樣的:

Cipher cipher = Cipher.getInstance("RSA"); 
cipher.init(Cipher.DECRYPT_MODE, key); 
Path path = Paths.get("fileToDecrypt.p7m"); 
byte[] data = Files.readAllBytes(path); 
byte[] decryptedData = cipher.doFinal(data); 

我得到:

javax.crypto.IllegalBlockSizeException: Data must not be longer than 256 bytes

我有這兩個文件:

  1. fileToDecrypt.p7m
  2. privateKey.pem:包含RSA私鑰和兩個X508證書

我不知道從哪裏開始解密什麼,以及如何?

+1

你可以回答你自己的問題;) –

回答

1

解決的問題:

private static byte[] cmsDecrypt(byte[] message, PrivateKey key) throws 
     Exception { 
    CMSEnvelopedDataParser ep = new CMSEnvelopedDataParser(message); 
    RecipientInformationStore recipients = ep.getRecipientInfos(); 
    Collection c = recipients.getRecipients(); 
    Iterator iter = c.iterator(); 
    RecipientInformation recipient = (RecipientInformation) iter.next(); 
    return recipient.getContent(key, new BouncyCastleProvider()); 
} 



    Path path = Paths.get("fileToDecrypt.p7m"); 
    byte[] data = Files.readAllBytes(path); 
    try { 
     System.out.println(new String(cmsDecrypt(data, key))); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    }