List of usage examples for org.bouncycastle.mail.smime SMIMECompressed SMIMECompressed
public SMIMECompressed(MimeMessage message) throws MessagingException, CMSException
From source file:chapter9.CompressedMailExample.java
/** * * @param args// w w w.j av a 2 s. c o m * @throws Exception */ public static void main(String[] args) throws Exception { //1.- Create the message we want compressed MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello World!!"); //2.- Set up the generator SMIMECompressedGenerator gen = new SMIMECompressedGenerator(); //3.- Generate the compressed message MimeBodyPart comPart = gen.generate(dataPart, SMIMECompressedGenerator.ZLIB); //4-. Create the mail message MimeMessage mail = Utils.createMimeMessage("example compressed message", comPart.getContent(), comPart.getContentType()); //5.- Create the enveloped object from the mail message SMIMECompressed compressed = new SMIMECompressed(mail); //6.- Uncompression step MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(compressed.getContent()); //7.- Content display step System.out.print("Content: "); System.out.println(recoveredPart.getContent()); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/** * Uncompresses message data/* w w w . ja va 2s .com*/ */ public byte[] decompressData(AS2MessageInfo info, byte[] data, String contentType) throws Exception { MimeBodyPart compressedPart = new MimeBodyPart(); compressedPart.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType))); compressedPart.setHeader("content-type", contentType); return (this.decompressData(info, new SMIMECompressed(compressedPart), compressedPart.getSize())); }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/** * Analyzes and creates passed message data *//* ww w . j a v a2 s.com*/ public AS2Message createMessageFromRequest(byte[] rawMessageData, Properties header, String contentType) throws AS2Exception { AS2Message message = new AS2Message(new AS2MessageInfo()); if (this.configConnection == null) { throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "AS2MessageParser: Pass a DB connection before calling createMessageFromRequest()", message); } try { //decode the content transfer encoding if set try { rawMessageData = this.processContentTransferEncoding(rawMessageData, header); } catch (Exception e) { message.getAS2Info().setMessageId("UNKNOWN"); throw e; } //check if this is a MDN MDNParser mdnParser = new MDNParser(); AS2MDNInfo mdnInfo = mdnParser.parseMDNData(rawMessageData, contentType); //its a MDN if (mdnInfo != null) { message.setAS2Info(mdnInfo); mdnInfo.initializeByRequestHeader(header); return (this.createFromMDNRequest(rawMessageData, header, contentType, mdnInfo, mdnParser)); } else { AS2MessageInfo messageInfo = (AS2MessageInfo) message.getAS2Info(); messageInfo.initializeByRequestHeader(header); //inbound AS2 message, no MDN //no futher processing if the message does not contain a message id if (messageInfo.getMessageId() == null) { return (message); } //figure out if the MDN should be signed NOW. If an error occurs beyond this point //the info has to know if the returned MDN should be signed messageInfo.getDispositionNotificationOptions() .setHeaderValue(header.getProperty("disposition-notification-options")); //indicates if a sync or async mdn is requested as answer messageInfo.setAsyncMDNURL(header.getProperty("receipt-delivery-option")); messageInfo.setRequestsSyncMDN(header.getProperty("receipt-delivery-option") == null || header.getProperty("receipt-delivery-option").trim().length() == 0); //check for existing partners PartnerAccessDB partnerAccess = new PartnerAccessDB(this.configConnection, this.runtimeConnection); Partner sender = partnerAccess.getPartner(messageInfo.getSenderId()); Partner receiver = partnerAccess.getPartner(messageInfo.getReceiverId()); if (sender == null) { throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR, "Sender AS2 id " + messageInfo.getSenderId() + " is unknown.", message); } if (receiver == null) { throw new AS2Exception(AS2Exception.UNKNOWN_TRADING_PARTNER_ERROR, "Receiver AS2 id " + messageInfo.getReceiverId() + " is unknown.", message); } if (!receiver.isLocalStation()) { throw new AS2Exception( AS2Exception.PROCESSING_ERROR, "The receiver of the message (" + receiver.getAS2Identification() + ") is not defined as a local station.", message); } MessageAccessDB messageAccess = new MessageAccessDB(this.configConnection, this.runtimeConnection); //check if the message already exists AS2MessageInfo alreadyExistingInfo = this.messageAlreadyExists(messageAccess, messageInfo.getMessageId()); if (alreadyExistingInfo != null) { //perform notification: Resend detected, manual interaction might be required Notification notification = new Notification(this.configConnection, this.runtimeConnection); notification.sendResendDetected(messageInfo, alreadyExistingInfo, sender, receiver); if (this.logger != null) { //do not log before because the logging process is related to an already created message in the transaction log this.logger.log( Level.FINE, this.rb .getResourceString("msg.incoming", new Object[] { messageInfo.getMessageId(), AS2Tools.getDataSizeDisplay(rawMessageData.length) }), messageInfo); } throw new AS2Exception(AS2Exception.PROCESSING_ERROR, "An AS2 message with the message id " + messageInfo.getMessageId() + " has been already processed successfully by the system or is pending (" + alreadyExistingInfo.getInitDate() + "). Please " + " resubmit the message with a new message id instead or resending it if it should be processed again.", new AS2Message(messageInfo)); } messageAccess.initializeOrUpdateMessage(messageInfo); if (this.logger != null) { //do not log before because the logging process is related to an already created message in the transaction log this.logger.log( Level.FINE, this.rb .getResourceString("msg.incoming", new Object[] { messageInfo.getMessageId(), AS2Tools.getDataSizeDisplay(rawMessageData.length) }), messageInfo); } message.setRawData(rawMessageData); byte[] decryptedData = this.decryptMessage(message, rawMessageData, contentType, sender, receiver); //may be already compressed here. Decompress first before going further if (this.contentTypeIndicatesCompression(contentType)) { byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), decryptedData, contentType); message.setDecryptedRawData(decompressed); //content type has changed now, get it from the decompressed data ByteArrayInputStream memIn = new ByteArrayInputStream(decompressed); MimeBodyPart tempPart = new MimeBodyPart(memIn); memIn.close(); contentType = tempPart.getContentType(); } else { //check the MIME structure that is embedded in decryptedData for its content type ByteArrayInputStream memIn = new ByteArrayInputStream(decryptedData); MimeMessage possibleCompressedPart = new MimeMessage( Session.getInstance(System.getProperties()), memIn); memIn.close(); if (this.contentTypeIndicatesCompression(possibleCompressedPart.getContentType())) { long compressedSize = possibleCompressedPart.getSize(); byte[] decompressed = this.decompressData((AS2MessageInfo) message.getAS2Info(), new SMIMECompressed(possibleCompressedPart), compressedSize); message.setDecryptedRawData(decompressed); } else { message.setDecryptedRawData(decryptedData); } } decryptedData = null; Part payloadPart = this.verifySignature(message, sender, contentType); //decompress the data if it has been sent compressed, only possible for signed data if (message.getAS2Info().getSignType() != AS2Message.SIGNATURE_NONE) { //signed message: //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.1 MIC Calculation For Signed Message //For any signed message, the MIC to be returned is calculated over //the same data that was signed in the original message as per [AS1]. //The signed content will be a mime bodypart that contains either //compressed or uncompressed data. this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType); payloadPart = this.decompressData(payloadPart, message); this.writePayloadsToMessage(payloadPart, message, header); } else { //this is an unsigned message this.writePayloadsToMessage(message.getDecryptedRawData(), message, header); //unsigned message: //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.2 MIC Calculation For Encrypted, Unsigned Message //For encrypted, unsigned messages, the MIC to be returned is //calculated over the uncompressed data content including all //MIME header fields and any applied Content-Transfer-Encoding. //http://tools.ietf.org/html/draft-ietf-ediint-compression-12 //4.3 MIC Calculation For Unencrypted, Unsigned Message //For unsigned, unencrypted messages, the MIC is calculated //over the uncompressed data content including all MIME header //fields and any applied Content-Transfer-Encoding. this.computeReceivedContentMIC(rawMessageData, message, payloadPart, contentType); } if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("found.attachments", new Object[] { messageInfo.getMessageId(), String.valueOf(message.getPayloadCount()) }), messageInfo); } return (message); } } catch (Exception e) { e.printStackTrace(); if (e instanceof AS2Exception) { throw (AS2Exception) e; } else { throw new AS2Exception(AS2Exception.PROCESSING_ERROR, e.getMessage(), message); } } }
From source file:de.mendelson.comm.as2.message.AS2MessageParser.java
/** * Looks if the data is compressed and decompresses it if necessary *///from w ww.j a v a2s . co m public Part decompressData(Part part, AS2Message message) throws Exception { Part compressedPart = this.getCompressedEmbeddedPart(part); if (compressedPart == null) { return (part); } SMIMECompressed compressed = null; if (compressedPart instanceof MimeBodyPart) { compressed = new SMIMECompressed((MimeBodyPart) compressedPart); } else { compressed = new SMIMECompressed((MimeMessage) compressedPart); } byte[] decompressedData = compressed.getContent(new ZlibExpanderProvider()); ((AS2MessageInfo) message.getAS2Info()).setCompressionType(AS2Message.COMPRESSION_ZLIB); if (this.logger != null) { this.logger.log(Level.INFO, this.rb.getResourceString("data.compressed.expanded", new Object[] { message.getAS2Info().getMessageId(), AS2Tools.getDataSizeDisplay(part.getSize()), AS2Tools.getDataSizeDisplay(decompressedData.length) }), message.getAS2Info()); } ByteArrayInputStream memIn = new ByteArrayInputStream(decompressedData); MimeBodyPart uncompressedPayload = new MimeBodyPart(memIn); memIn.close(); return (uncompressedPayload); }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testCompressAS2Message() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); partnershipDVO.setIsOutboundCompressRequired(true); String mid = RANDOM.toString(); AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); SMIMECompressed compressed = new SMIMECompressed(as2Msg.getBodyPart()); MimeBodyPart decompressedPart = SMIMEUtil.toMimeBodyPart(compressed.getContent()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOHandler.pipe(decompressedPart.getDataHandler().getInputStream(), baos); byte[] decrptedBA = baos.toByteArray(); byte[] original = IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG)); Assert.assertTrue(Arrays.equals(decrptedBA, original)); //TODO/*from w w w . j ava 2s . co m*/ String filenameHdr = decompressedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Filename value lost in BodyPart Header", MOCK_AS2_MSG, getFileName(filenameHdr)); // Verify MIC Value ByteArrayOutputStream contentBAOS = new ByteArrayOutputStream(); decompressedPart.writeTo(contentBAOS); byte[] content = (contentBAOS.toByteArray()); String mic = calculateMIC(content); Assert.assertEquals("MIC Value is not valid.", mic, getStoredMessage(mid).getMicValue()); }
From source file:hk.hku.cecid.edi.as2.module.test.OutgoingMessageProcessorTest.java
License:Open Source License
@Test public void testSignedCommpressMessage() throws Exception { InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG); ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins)); // Prepare Data String mid = RANDOM.toString(); partnershipDVO.setIsOutboundSignRequired(true); partnershipDVO.setIsOutboundCompressRequired(true); //Process message AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG)); try {/*from w w w . jav a 2 s.co m*/ //Verify Message Signature SMIMESigned signed = new SMIMESigned((MimeMultipart) as2Msg.getBodyPart().getContent()); SignerInformationStore signers = signed.getSignerInfos(); Iterator signerInfos = signers.getSigners().iterator(); while (signerInfos.hasNext()) { SignerInformation signerInfo = (SignerInformation) signerInfos.next(); if (!signerInfo.verify(partnershipDVO.getEffectiveVerifyCertificate(), "BC")) { Assert.fail("Signature Verfifcation Failed"); } } // Verify MIC Value MimeBodyPart signedPart = signed.getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); signedPart.writeTo(baos); byte[] content = (baos.toByteArray()); String mic = calculateMIC(content); MessageDVO msgDVO = getStoredMessage(mid); Assert.assertEquals("MIC Value is not valid.", mic, msgDVO.getMicValue()); //Decompress Message SMIMECompressed compressed = new SMIMECompressed(signedPart); MimeBodyPart decompressedPart = SMIMEUtil.toMimeBodyPart(compressed.getContent()); //Assert the filename value String filenameHdr = decompressedPart.getHeader("Content-Disposition")[0]; Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr)); } catch (Exception exp) { Assert.fail("Signature Verfifcation Failed"); } }
From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java
License:Open Source License
/** * Decompresses the encapsulated MIME body part. * /* w ww. ja v a 2s .co m*/ * @return an S/MIME message encapsulating the decompressed MIME body part. * @throws SMimeException if unable to decompress the body part. */ public SMimeMessage decompress() throws SMimeException { try { setDefaults(); SMIMECompressed m = new SMIMECompressed(bodyPart); ByteArrayInputStream ins = new ByteArrayInputStream(m.getContent()); MimeBodyPart decompressedPart = new MimeBodyPart(ins); return new SMimeMessage(decompressedPart, this); } catch (Exception e) { throw new SMimeException("Unable to decompress body part", e); } }
From source file:io.aos.crypto.spl09.CompressedMailExample.java
License:Apache License
public static void main(String args[]) throws Exception { // create the message we want compressed MimeBodyPart dataPart = new MimeBodyPart(); dataPart.setText("Hello world!"); // set up the generator SMIMECompressedGenerator gen = new SMIMECompressedGenerator(); // generate the compressed message MimeBodyPart comPart = gen.generate(dataPart, SMIMECompressedGenerator.ZLIB); // create the mail message MimeMessage mail = Utils.createMimeMessage("example compressed message", comPart.getContent(), comPart.getContentType());// w w w. ja v a2 s. c om // create the enveloped object from the mail message SMIMECompressed compressed = new SMIMECompressed(mail); // uncompression step MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(compressed.getContent()); // content display step System.out.print("Content: "); System.out.println(recoveredPart.getContent()); }
From source file:mitm.common.security.cms.CMSCompressedInspectorImplTest.java
License:Open Source License
@Test public void testDecompress() throws FileNotFoundException, MessagingException, CMSException { MimeMessage compressedMessage = loadMessage("compressed.eml"); SMIMECompressed compressed = new SMIMECompressed(compressedMessage); CMSCompressedDataAdapter cmsCompressed = CMSAdapterFactory.createAdapter(compressed); assertTrue(cmsCompressed instanceof CMSCompressedDataAdapterImpl); }