Example usage for org.bouncycastle.cms RecipientInformationStore get

List of usage examples for org.bouncycastle.cms RecipientInformationStore get

Introduction

In this page you can find the example usage for org.bouncycastle.cms RecipientInformationStore get.

Prototype

public RecipientInformation get(RecipientId selector) 

Source Link

Document

Return the first RecipientInformation object that matches the passed in selector.

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/*from   w  ww .  j a va 2s .  c  om*/
            .toMimeBodyPart(recipient.getContent(new JceKeyTransEnvelopedRecipient(privateKey)));
    MimeMultipart content = (MimeMultipart) res.getContent();
    Multipart decryptedContent = null;
    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.EnvelopedMailExample.java

/**
 *
 * @param args/*w  ww. j  a  v  a  2s  . co  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//from   w  ww  .  j av  a 2s .com
 * @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:chapter9.KEKEnvelopedDataExample.java

/**
 *
 * @param args//from  ww  w  .j  a  v a 2s .c o m
 * @throws Exception
 */
public static void main(String[] args) throws Exception {
    KeyGenerator keyGen = KeyGenerator.getInstance(CryptoDefs.Algorithm.DESede.getName(),
            CryptoDefs.Provider.BC.getName());
    SecretKey key = keyGen.generateKey();

    //1.- Set up the generator
    CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();

    byte[] kekID = new byte[] { 1, 2, 3, 4, 5 };

    edGen.addKEKRecipient(key, kekID);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = edGen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

    //4.- Look for our recipient identifier
    RecipientId recId = new KEKRecipientId(kekID);

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

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

From source file:chapter9.KeyTransEnvelopedDataExample.java

/**
 *
 * @param args//from  w  w w . j  a  v a 2 s. co  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.- Set up the generator
    CMSEnvelopedDataGenerator gen = new CMSEnvelopedDataGenerator();

    gen.addKeyTransRecipient(cert);

    //2.- Create the enveloped-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!!".getBytes());
    CMSEnvelopedData enveloped = gen.generate(data, CMSEnvelopedDataGenerator.AES128_CBC,
            CryptoDefs.Provider.BC.getName());

    //3.- Re-create
    enveloped = new CMSEnvelopedData(enveloped.getEncoded());

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

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

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

    if (recipient != null) {
        //5.- Decrypt the data
        byte[] recData = recipient.getContent(key, CryptoDefs.Provider.BC.getName());

        //6.- Compare recovered data to the original data
        if (Arrays.equals((byte[]) data.getContent(), recData))
            System.out.println("\t data recovery succeeded!!");
        else
            System.out.println("\t data recovery failed!!");
    } else
        System.out.println("\t Could not find a matching recipient!!");
}

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

License:Apache License

/**
 * Test to fetch e-mails from a POP3 mainbox.
 *
 * @throws  Exception//from ww w .ja  v a  2 s .  co 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.comm.as2.message.AS2MessageParser.java

/**
 * Decrypts the data of a message with all given certificates etc
 *
 * @param info MessageInfo, the encryption algorith will be stored in the
 * encryption type of this info//from   w w  w . j  a v a 2s.co m
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 */
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    JceKeyTransRecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE,
                        this.rb.getResourceString("decryption.inforequired", new Object[] { info.getMessageId(),
                                ((KeyTransRecipientId) recipientInfo.getRID()).getIssuer() + ", "
                                        + ((KeyTransRecipientId) recipientInfo.getRID()).getSerialNumber() }),
                        info);
            }
        }
        if (this.logger != null) {
            this.logger.log(
                    Level.SEVERE, this.rb
                            .getResourceString("decryption.infoassigned",
                                    new Object[] { info.getMessageId(), receiverCryptAlias,
                                            recipientId.getIssuer() + ", " + recipientId.getSerialNumber() }),
                    info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}

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

License:BSD License

/**
 * Decrypts the encrypted MimeMessage based on supplied key
 * /*from  ww w.j a  v a2  s  .  c  om*/
 * @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 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/* w  w  w. j  a v  a 2s  .c om*/
    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 {/*ww  w  .  j a  v  a 2 s  . c o  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);
}