Example usage for org.bouncycastle.mail.smime SMIMEUtil toMimeBodyPart

List of usage examples for org.bouncycastle.mail.smime SMIMEUtil toMimeBodyPart

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime SMIMEUtil toMimeBodyPart.

Prototype

public static FileBackedMimeBodyPart toMimeBodyPart(CMSTypedStream content) throws SMIMEException 

Source Link

Document

return a file backed MimeBodyPart described in CMSTypedStream content.

Usage

From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java

License:Open Source License

private Multipart getDecryptedContent(Message message, X509Certificate signCert, X509Certificate encryptCert,
        PrivateKey privateKey) throws OperatorCreationException, Exception {
    RecipientId recId = new JceKeyTransRecipientId(encryptCert);
    SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);

    RecipientInformationStore recipients = m.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    MimeBodyPart res = SMIMEUtil
            .toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey)));
    MimeMultipart content = (MimeMultipart) res.getContent();
    Multipart decryptedContent = null;//  w ww  .j  a  va  2  s.co m
    if (checkSignature(content, signCert)) {
        for (int i = 0; i < content.getCount(); i++) {
            Part part = content.getBodyPart(i);

            String contentType = part.getContentType();

            if (contentType.toLowerCase().startsWith("multipart/mixed")) {
                decryptedContent = (Multipart) part.getContent();
            }

        }
    }

    return decryptedContent;
}

From source file:chapter9.CompressedMailExample.java

/**
 *
 * @param args//w ww. j av a2s. 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:chapter9.EnvelopedMailExample.java

/**
 *
 * @param args// w  ww. j  a v  a  2  s  .c o  m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);

    X509Certificate cert = (X509Certificate) chain[0];

    //1.- Create the message we want encrypted
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello World!!");

    //2.- Set up the generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);

    //3.- Generate the enveloped message
    MimeBodyPart envPart = gen.generate(dataPart, SMIMEEnvelopedGenerator.AES256_CBC,
            CryptoDefs.Provider.BC.getName());

    //4.- Create the mail message
    MimeMessage mail = Utils.createMimeMessage("example enveloped message", envPart.getContent(),
            envPart.getContentType());

    //5.- Create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    //6.- Look for our recipient identifier
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    if (recipient != null) {
        //7.- Decryption step
        MimeBodyPart recoveredPart = SMIMEUtil
                .toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName()));

        //8.- Content display step
        System.out.print("\t Content:");
        System.out.println(recoveredPart.getContent());
    } else
        System.out.println("\t could not find a matching recipient!!");
}

From source file:chapter9.EnvelopedSignedMailExample.java

/**
 *
 * @param args/* www  .j a v a2 s.c o  m*/
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);

    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), CryptoDefs.Provider.BC.getName());

    X509Certificate cert = (X509Certificate) chain[0];

    //1.- Create the message we want signed
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello World!!");

    //2.- Create the signed message
    MimeMultipart signedMulti = SignedMailExample.createMultipartWithSignature(key, cert, certsAndCRLs,
            dataPart);

    //3.- Create the body part containing the signed message
    MimeBodyPart signedPart = new MimeBodyPart();

    signedPart.setContent(signedMulti);

    //4.- Set up the generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);

    //5.- Generate the enveloped message
    MimeBodyPart envPart = gen.generate(signedPart, SMIMEEnvelopedGenerator.AES256_CBC,
            CryptoDefs.Provider.BC.getName());

    //6.- Create the mail message
    MimeMessage mail = Utils.createMimeMessage("example signed and enveloped message", envPart.getContent(),
            envPart.getContentType());

    //7.- Create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    //8.- Look for our recipient identifier
    RecipientId recId = new KeyTransRecipientId(new X500Name(cert.getIssuerX500Principal().getName()),
            cert.getSerialNumber());

    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    //9.- Decryption step
    MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, CryptoDefs.Provider.BC.getName()));

    //10.- Extract the multipart from the body part
    if (res.getContent() instanceof MimeMultipart) {
        SMIMESigned signed = new SMIMESigned((MimeMultipart) res.getContent());

        //11.- Verification step
        X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

        if (isValid(signed, rootCert))
            System.out.println("\t verification succeeded!!");
        else
            System.out.println("\t verification failed!!");

        //12.- Content display step
        MimeBodyPart content = signed.getContent();

        System.out.print("\t Content: ");
        System.out.println(content.getContent());
    } else
        System.out.println("\t wrong content found!!");
}

From source file:com.cordys.coe.test.smime.TestSMIMEBouncyCastle.java

License:Apache License

/**
 * Test to fetch e-mails from a POP3 mainbox.
 *
 * @throws  Exception//  www. j  a v a2 s  .  c o m
 */
public void fetchAllMessage() throws Exception {
    int config = 0;

    try {
        config = DOC
                .parseString("<emailboxes xmlns=\"http://emailioconnector.coe.cordys.com/2.0/configuration\">"
                        + "<emailbox>" + "<name>testmailbox</name>" + "<host>srv-nl-ces70</host>"
                        + "<port>110</port>" + "<type>POP3</type>" + "<username>cordystestuser1</username>"
                        + "<password>Y29yZHlzdGVzdHVzZXIx</password>" + "<pollinterval>5000</pollinterval>"
                        + "<folders>" + "<folder>Inbox</folder>" + "</folders>" + "</emailbox>"
                        + "</emailboxes>");

        int emailBoxConfigNode = Node.getFirstElement(config);

        IEmailBox e = new POP3EmailBox(emailBoxConfigNode, 0, "", true);
        IEmailConnection ec = EmailConnectionFactory.createConnection(e);
        Message[] am = ec.getEmailHeaders();

        for (int iCount = 0; iCount < am.length; iCount++) {
            MimeMessage msg = (MimeMessage) am[iCount];

            if (LOG.isEnabled(Severity.DEBUG)) {
                LOG.log(Severity.DEBUG, "= Message " + (iCount + 1) + " =");

                LOG.log(Severity.DEBUG, msg.getSubject() + " from " + msg.getFrom()[0].toString() + " to "
                        + msg.getRecipients(RecipientType.TO)[0].toString());
            }

            // TODO: We need to detect whether or not the mail is encrypted/signed. To do this
            // we need to example the content type of the mail.

            // We need to figure out which certificate to use for receiving the mail. We'll go
            // through all known identities to see if we're there.
            Map<String, ICertificateInfo> identities = m_km.getIdentities();

            // Parse the mail message
            SMIMEEnveloped m = new SMIMEEnveloped(msg);

            // Find the details of a receipient that can decrypt the message.
            RecipientInformationStore recipients = m.getRecipientInfos();
            RecipientInformation recipient = null;
            ICertificateInfo certInfo = null;

            for (ICertificateInfo tmp : identities.values()) {
                recipient = recipients.get(tmp.getRecipientId());

                if (recipient != null) {
                    certInfo = tmp;
                    System.out.println(
                            "Found a recipient: " + certInfo.getAlias() + "/" + certInfo.getEmailAddress());
                    break;
                }
            }

            // Now do the actual decryption of the message.
            Key privateKey = certInfo.getKey();

            MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(privateKey, "BC"));

            // Do the signature
            doSignatureValidation(res);

            // So now the mail is decrypted. If it's signed we also do the signature check. Once
            // that's done we create a NEW dummy MimeMessage which is identical to the original
            // mail, but with the Encrypted part removed.
            MimeMessage mmNew = new MimeMessage(msg);

            MimeMultipart mmTemp = new MimeMultipart();
            mmTemp.addBodyPart(res);
            mmNew.setContent(mmTemp);

            mmNew.saveChanges();

            // The part will be a stream. And the stream contains a mail message.

            if (res != null) {
                LOG.log(Severity.DEBUG, "= Decrypted message " + (iCount + 1));
                LOG.log(Severity.DEBUG, "===============================");
                LOG.log(Severity.DEBUG, MailMessageUtil.dumpMessage(mmNew));
                LOG.log(Severity.DEBUG, "===============================");
                LOG.log(Severity.DEBUG, "Original raw:\n" + MailMessageUtil.rawMessage(msg)
                        + "\n\n\nDecrypted raw:\n" + MailMessageUtil.rawMessage(mmNew));
            } else {
                System.out.println("failed to decrypt message.");
            }
        }
    } finally {
        if (config > 0) {
            Node.delete(config);
        }
    }
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Used for mendelson rosettaNet//from www  .java  2 s  .  c  o  m
 */
public MimeBodyPart decrypt(MimeBodyPart part, Certificate cert, Key key)
        throws GeneralSecurityException, MessagingException, CMSException, IOException, SMIMEException {
    if (!this.isEncrypted(part)) {
        throw new GeneralSecurityException(
                "decrypt: Unable to decrypt - Content-Type indicates data isn't encrypted");
    }
    X509Certificate x509Cert = castCertificate(cert);
    SMIMEEnveloped envelope = new SMIMEEnveloped(part);
    RecipientId recipientId = new JceKeyTransRecipientId(x509Cert);
    RecipientInformation recipient = envelope.getRecipientInfos().get(recipientId);
    if (recipient == null) {
        throw new GeneralSecurityException(
                "decrypt: Unable to decrypt data - wrong key used to decrypt the data.");
    } else {
        MimeBodyPart bodyPart = SMIMEUtil.toMimeBodyPart(recipient.getContentStream(
                new JceKeyTransEnvelopedRecipient(this.getPrivateKey(key)).setProvider("BC")));
        return (bodyPart);
    }
}

From source file:gov.nih.nci.cacis.nav.DecryptMail.java

License:BSD License

/**
 * Decrypts the encrypted MimeMessage based on supplied key
 * /*  w  ww.  j a  va 2s .  com*/
 * @param msg - encrypte MimeMessage
 * @param keystorepath - keystore to be used
 * @param storepass - keystore password (same as key)
 * @param keyAlias - alias for the key to be used
 * @return - Decrypted MimeBodyPart
 * @throws Exception - exception thrown, if any
 */
public MimeBodyPart decrypt(MimeMessage msg, String keystorepath, String storepass, String keyAlias)
        throws Exception { // NOPMD
    //
    // Open the key store
    //
    final KeyStore ks = KeyStore.getInstance(STORE_TYPE, PROVIDER_TYPE);
    // final InputStream is = getClass().getClassLoader().getResourceAsStream(keystorePath);
    final InputStream is = new FileInputStream(keystorepath);
    ks.load(is, storepass.toCharArray());

    //
    // find the certificate for the private key and generate a
    // suitable recipient identifier.
    //
    final X509Certificate cert = (X509Certificate) ks.getCertificate(keyAlias);
    final RecipientId recId = new RecipientId();

    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

    final SMIMEEnveloped m = new SMIMEEnveloped(msg);

    final RecipientInformationStore recipients = m.getRecipientInfos();
    final RecipientInformation recipient = recipients.get(recId);

    final MimeBodyPart res = SMIMEUtil
            .toMimeBodyPart(recipient.getContent(ks.getKey(keyAlias, null), PROVIDER_TYPE));

    LOG.debug("Message Contents");
    LOG.debug("----------------");
    LOG.debug(res.getContent());

    return res;
}

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  av a  2  s .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 testEncrytedAS2Message() throws Exception {
    InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG);
    ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins));
    String mid = RANDOM.toString();

    partnershipDVO.setIsOutboundEncryptRequired(true);
    AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID
            "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG));

    // Decrypt Message
    SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart());
    RecipientId recId = new RecipientId();
    recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber());
    recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded());

    RecipientInformationStore recipients = crypted.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager");
    MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC"));

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    IOHandler.pipe(decrpted.getDataHandler().getInputStream(), baos);
    byte[] decrptedBA = baos.toByteArray();
    byte[] originalBA = IOHandler.readBytes(FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG));

    Assert.assertTrue(Arrays.equals(decrptedBA, originalBA));

    //Assert the filename
    String filenameHdr = decrpted.getHeader("Content-Disposition")[0];
    Assert.assertEquals("Filename value lost in BodyPartHeader", MOCK_AS2_MSG, getFileName(filenameHdr));

    //Verify MIC// ww  w.ja  v a2s . c  o  m
    ByteArrayOutputStream contentStream = new ByteArrayOutputStream();
    decrpted.writeTo(contentStream);
    byte[] content = (contentStream.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 testSignedEncryptedAS2Message() throws Exception {
    InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG);
    ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins));

    // Prepare Data
    String mid = RANDOM.toString();
    partnershipDVO.setIsOutboundEncryptRequired(true);
    partnershipDVO.setIsOutboundSignRequired(true);
    //Encrypt message
    AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID
            "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG));

    // Decrypt Message
    SMIMEEnveloped crypted = new SMIMEEnveloped(as2Msg.getBodyPart());
    RecipientId recId = new RecipientId();
    recId.setSerialNumber(partnershipDVO.getEncryptX509Certificate().getSerialNumber());
    recId.setIssuer(partnershipDVO.getEncryptX509Certificate().getIssuerX500Principal().getEncoded());

    RecipientInformationStore recipients = crypted.getRecipientInfos();
    RecipientInformation recipient = recipients.get(recId);

    KeyStoreManager keyMan = (KeyStoreManager) TARGET.getSystemModule().getComponent("keystore-manager");
    MimeBodyPart decrpted = SMIMEUtil.toMimeBodyPart(recipient.getContent(keyMan.getPrivateKey(), "BC"));

    //Verify Signature
    try {/* w ww  . ja  v a2s .co  m*/
        SMIMESigned signed = new SMIMESigned((MimeMultipart) decrpted.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");
            }
        }

        //Assert the filename value
        MimeBodyPart signedPart = signed.getContent();
        String filenameHdr = signedPart.getHeader("Content-Disposition")[0];
        Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr));

        // Verify MIC Value
        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());

    } catch (Exception exp) {
        Assert.fail("Signature Verfifcation Failed");
    }
    Assert.assertTrue(true);
}