Advertisement
ballchaichana

smime

Nov 11th, 2018
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.84 KB | None | 0 0
  1.     public static void startSMimeDecryption (final String encryptedPath, String decryptedPath) {
  2.     logger.info("***  Start of sMIME decryption  ***"); //$NON-NLS-1$
  3.  
  4.     Properties props = System.getProperties();
  5.     Session session = Session.getDefaultInstance(props, null);
  6.     try {
  7.  
  8.         logger.info("Encrypted message: [" + encryptedPath + "]"); //$NON-NLS-1$ //$NON-NLS-2$
  9.         File messageFile = new File(encryptedPath);
  10.         String fileExtension = getFileExtension(messageFile);
  11.  
  12.         if (fileExtension != null) {
  13.  
  14.             MimeMessage m = null;
  15.  
  16.             if (fileExtension.toUpperCase().equals("EML")) { //$NON-NLS-1$
  17.  
  18.                 try (FileInputStream streamIn = new FileInputStream(encryptedPath);) {
  19.                     logger.info("Created FileInputStream."); //$NON-NLS-1$
  20.  
  21.                     m = new MimeMessage(session, streamIn);
  22.                     logger.info("Created MimeMessage."); //$NON-NLS-1$
  23.                 } catch (IOException e) {
  24.                     logger.error("Error while trying to read in message via stream. " + e.getMessage());
  25.                     return;
  26.                 }  
  27.  
  28.             } else if (fileExtension.toUpperCase().equals("MSG")) { //$NON-NLS-1$
  29.                 m = createMimeMessageFromMsg(session, messageFile);
  30.                 logger.info("Created MimeMessage."); //$NON-NLS-1$
  31.             } else {
  32.                 throw new InvalidFileException("Not a supported file type (extension). Only '*.eml' and '*.msg' are accepted."); //$NON-NLS-1$
  33.             }
  34.  
  35.             if ((m.getFileName() != null) && (m.getFileName().toUpperCase().equals("SMIME.P7M") || Pattern.compile("^\\s*application\\/(x-)?pkcs7-mime.*$", Pattern.DOTALL).matcher(m.getContentType()).matches())) { //$NON-NLS-1$ //$NON-NLS-2$
  36.  
  37.                 m = decryptMessage(m);
  38.  
  39.                 logger.info("Saving decrypted message to file..."); //$NON-NLS-1$
  40.                 if (decryptedPath == null) {
  41.                     String tempPath = messageFile.getAbsolutePath().substring(0, messageFile.getAbsolutePath().lastIndexOf(File.separator));
  42.                     decryptedPath = tempPath + File.separator + FilenameUtils.removeExtension(messageFile.getName()) + "_decrypted.eml"; //$NON-NLS-1$
  43.                 }
  44.  
  45.                 try (OutputStream str = Files.newOutputStream(Paths.get(decryptedPath))) {
  46.  
  47.                     m.writeTo(str);
  48.  
  49.                 } catch (IOException e) {
  50.                     logger.error("Failed to write to output stream. " + e.getMessage()); //$NON-NLS-1$
  51.                     return;
  52.                 }
  53.  
  54.                 logger.info("Decrypted message: [" + decryptedPath + "]"); //$NON-NLS-1$ //$NON-NLS-2$
  55.  
  56.             } else {
  57.                 throw new NotEncryptedMessageException("Not an encrypted message. Breaking up decryption."); //$NON-NLS-1$
  58.             }
  59.  
  60.         } else {
  61.             throw new InvalidFileException("No file extension found."); //$NON-NLS-1$
  62.         }
  63.  
  64.     } catch (MessagingException | UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException
  65.              | CMSException | InvalidFileException | InvalidMessageException e) {
  66.  
  67.         logger.error("Failed to read message. " + e.getMessage()); //$NON-NLS-1$
  68.     } catch (NotEncryptedMessageException e) {
  69.         logger.error(e.getMessage());
  70.         System.exit(RETURNCODE_NODECRYPTION);
  71.     }
  72.  
  73.     logger.info("***  End of sMIME decryption  ***"); //$NON-NLS-1$
  74. }
  75.  
  76. private static MimeMessage createMimeMessageFromMsg (final Session session, final File messageFile) {
  77.     MimeMessage mimeMsg = null;
  78.  
  79.     if (messageFile != null) {
  80.         MAPIMessage mapiMsg = null;
  81.  
  82.         logger.info("Converting .msg to MimeMessage."); //$NON-NLS-1$
  83.         try (NPOIFSFileSystem npoi = new NPOIFSFileSystem(messageFile)) {
  84.  
  85.             logger.info("Created NPOIFSFileSystem."); //$NON-NLS-1$
  86.  
  87.             mapiMsg = new MAPIMessage(npoi);
  88.             logger.info("Created MAPIMessage."); //$NON-NLS-1$
  89.  
  90.             mimeMsg = new MimeMessage(session);
  91.             logger.info("Creating MimeMessage..."); //$NON-NLS-1$
  92.  
  93.             // Header übertragen
  94.             try {
  95.                 for (String current : mapiMsg.getHeaders()) {
  96.                     try {
  97.  
  98.                         mimeMsg.addHeaderLine(current);
  99.  
  100.                     } catch (MessagingException e) {
  101.                         logger.error("Could not add header line to MimeMessage. " + e.getMessage()); //$NON-NLS-1$
  102.                     }
  103.                 }
  104.  
  105.                 logger.info("Added header to MimeMessage."); //$NON-NLS-1$
  106.  
  107.             } catch (ChunkNotFoundException e) {
  108.                 logger.error("Could not retrieve header. " + e.getMessage()); //$NON-NLS-1$
  109.             }
  110.  
  111.             // "Attachment" übertragen
  112.             for (AttachmentChunks current : mapiMsg.getAttachmentFiles()) {
  113.                 try {
  114.  
  115.                     ByteArrayDataSource ds = new ByteArrayDataSource(current.getEmbeddedAttachmentObject(), "application/pkcs7-mime"); //$NON-NLS-1$
  116.                     DataHandler dh = new DataHandler(ds);
  117.                     mimeMsg.setDataHandler(dh);
  118.  
  119.                     logger.info("Added attachment to MimeMessage."); //$NON-NLS-1$
  120.  
  121.                 } catch (MessagingException e) {
  122.                     logger.error("Could not transfer attachment into MimeMessage. " + e.getMessage()); //$NON-NLS-1$
  123.                 }
  124.             }
  125.  
  126.         } catch (IOException e) {
  127.             logger.error("Error while trying to build MimeMessage. " + e.getMessage()); //$NON-NLS-1$
  128.             mimeMsg = null;
  129.         }
  130.     }
  131.  
  132.     return mimeMsg;
  133. }
  134.  
  135. private static MimeMessage decryptMessage(final MimeMessage encrypted) throws MessagingException, CMSException,
  136.                                                                         KeyStoreException, UnrecoverableKeyException,
  137.                                                                         NoSuchAlgorithmException, InvalidMessageException {
  138.     if (encrypted != null) {
  139.         logger.info("Starting decrypting message..."); //$NON-NLS-1$
  140.         KeyStore keystore = getKeyStore();
  141.  
  142.         SMIMEEnveloped message = new SMIMEEnveloped(encrypted);
  143.  
  144.         RecipientInformationStore recinfos = message.getRecipientInfos();
  145.         Enumeration<String> aliases = keystore.aliases();
  146.         RecipientInformation recid = null;
  147.         String alias = null;
  148.  
  149.         logger.info("Decrypting message..."); //$NON-NLS-1$
  150.         while ((recid == null) && aliases.hasMoreElements()) {
  151.             alias = aliases.nextElement();
  152.             if (keystore.isKeyEntry(alias)) {
  153.                 Certificate cert = keystore.getCertificate(alias);
  154.                 recid = recinfos.get(new JceKeyTransRecipientId((X509Certificate) cert));
  155.             }
  156.         }
  157.         if (recid == null) {
  158.             throw new RuntimeException("No decryption key found"); //$NON-NLS-1$
  159.         }
  160.  
  161.         JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient((PrivateKey) keystore.getKey(alias, "changeit".toCharArray())); //$NON-NLS-1$
  162.  
  163.         byte[] content = recid.getContent(recipient);
  164.  
  165.         logger.info("Setting MimeMessage properties."); //$NON-NLS-1$
  166.         MimeMessage decrypted = new MimeMessage(Session.getDefaultInstance(System.getProperties()), new ByteArrayInputStream(content));
  167.         Enumeration<Header> headers = encrypted.getAllHeaders();
  168.         while (headers.hasMoreElements()) {
  169.             Header h = headers.nextElement();
  170.  
  171.             if (decrypted.getHeader(h.getName()) == null) {
  172.                 decrypted.addHeader(h.getName(), h.getValue());
  173.             }
  174.  
  175.         }
  176.  
  177.         decrypted.saveChanges();            
  178.  
  179.         logger.info("Decrypted message."); //$NON-NLS-1$
  180.  
  181.         return decrypted;
  182.     } else {
  183.         throw new InvalidMessageException("Encrypted MimeMessage is null."); //$NON-NLS-1$
  184.     }
  185. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement