2017-05-09 6 views
1

전자 메일 첨부 파일이 .p7m 형식이고 개인 키와 인증서를 포함하는 .pem 파일이 있습니다.Java 전자 메일 첨부 파일 (.p7m 파일) 암호 해독

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

그러나 자바 bouncycastle를 사용하여, 나는 그것을 해독 할 수 있습니다 : 사용 OpenSSL을 나는이 명령을 사용하여 파일의 암호를 해독 할 수 있습니다.

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 인증서

그리고 I를 포함 어디서 무엇을 해독 할 것인지, 그리고 어떻게 해독해야할지 모릅니다. 이 문제에

+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(); 
    }