Example usage for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos

List of usage examples for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos

Introduction

In this page you can find the example usage for org.bouncycastle.mail.smime SMIMEEnveloped getRecipientInfos.

Prototype

public RecipientInformationStore getRecipientInfos() 

Source Link

Document

return a store of the intended recipients for this message

Usage

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  w  w. j a  va  2s .  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);
}

From source file:hk.hku.cecid.piazza.commons.security.SMimeMessage.java

License:Open Source License

/**
 * Decrypts the encapsulated MIME body part.
 * //from  w w w. ja v a2 s .c  o  m
 * @param privateKey the private key for decryption.
 * @return an S/MIME message encapsulating the decrypted MIME body part. 
 * @throws SMimeException if unable to decrpyt the body part.
 */
public SMimeMessage decrypt(PrivateKey privateKey) throws SMimeException {
    if (privateKey == null) {
        throw new SMimeException("Private key not found");
    }

    try {
        setDefaults();

        SMIMEEnveloped m = new SMIMEEnveloped(bodyPart);
        RecipientId recId = new RecipientId();

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

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

        if (recipient == null) {
            throw new SMimeException("Invalid encrypted content");
        }
        ByteArrayInputStream ins = new ByteArrayInputStream(recipient.getContent(privateKey, "BC"));
        MimeBodyPart decryptedPart = new MimeBodyPart(ins);
        return new SMimeMessage(decryptedPart, this);
    } catch (Exception e) {
        throw new SMimeException("Unable to decrypt body part", e);
    }
}

From source file:io.aos.crypto.spl09.EnvelopedMailExample.java

License:Apache License

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];

    // create the message we want encrypted
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello world!");

    // set up the generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);/*w  ww  .j  a  va  2 s.c o  m*/

    // generate the enveloped message
    MimeBodyPart envPart = gen.generate(dataPart, SMIMEEnvelopedGenerator.AES256_CBC, "BC");

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

    // create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    // look for our recipient identifier
    RecipientId recId = new KEKRecipientId(null);

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

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

    if (recipient != null) {
        // decryption step
        MimeBodyPart recoveredPart = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC"));

        // content display step
        System.out.print("Content: ");
        System.out.println(recoveredPart.getContent());
    } else {
        System.out.println("could not find a matching recipient");
    }
}

From source file:io.aos.crypto.spl09.EnvelopedSignedMailExample.java

License:Apache License

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)), "BC");
    X509Certificate cert = (X509Certificate) chain[0];

    // create the message we want signed
    MimeBodyPart dataPart = new MimeBodyPart();

    dataPart.setText("Hello world!");

    // create the signed message
    MimeMultipart signedMultipart = SignedMailExample.createMultipartWithSignature(key, cert, certsAndCRLs,
            dataPart);//from  w  w w  .j av  a  2s .  c om

    // create the body part containing the signed message
    MimeBodyPart signedPart = new MimeBodyPart();

    signedPart.setContent(signedMultipart);

    // set up the enveloped message generator
    SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();

    gen.addKeyTransRecipient(cert);

    // generate the enveloped message
    MimeBodyPart envPart = gen.generate(signedPart, SMIMEEnvelopedGenerator.AES256_CBC, "BC");

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

    // create the enveloped object from the mail message
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mail);

    // look for our recipient identifier
    RecipientId recId = new KEKRecipientId(null);

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

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

    // decryption step
    MimeBodyPart res = SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC"));

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

        // verification step
        X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

        if (isValid(signed, rootCert)) {
            System.out.println("verification succeeded");
        } else {
            System.out.println("verification failed");
        }

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

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

From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java

License:Open Source License

private static byte[] decryptContent(SMIMEEnveloped smimeEnveloped, SmimeKey smimeKey)
        throws MessagingException, CMSException {
    X509Certificate certificate = smimeKey.getCertificate();
    PrivateKey privateKey = smimeKey.getPrivateKey();

    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipient = recipients.get(new JceKeyTransRecipientId(certificate));

    if (null == recipient) {
        throw new MessagingException("no recipient");
    }// w ww .j  a  va  2 s  . c om

    JceKeyTransRecipient transportRecipient = new JceKeyTransEnvelopedRecipient(privateKey);
    transportRecipient.setProvider(BouncyCastleProvider.PROVIDER_NAME);
    return recipient.getContent(transportRecipient);
}

From source file:org.apache.james.mailet.crypto.mailet.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 */// ww w . j  av a 2 s  . c  o  m
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            Collection<RecipientInformation> recipients = env.getRecipientInfos().getRecipients();
            for (Iterator<RecipientInformation> iter = recipients.iterator(); iter.hasNext();) {
                RecipientInformation info = (RecipientInformation) iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailet.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *///from   w ww.  j a v a2s .c  om
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            @SuppressWarnings("unchecked")
            Collection<RecipientInformation> recipients = env.getRecipientInfos().getRecipients();
            Iterator<RecipientInformation> iter = recipients.iterator();
            while (iter.hasNext()) {
                RecipientInformation info = iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        @SuppressWarnings("deprecation")
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailets.smime.SMIMEDecrypt.java

License:Apache License

public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;/*from   w w  w.  ja  v a 2s .  c o  m*/
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            Collection recipients = env.getRecipientInfos().getRecipients();
            for (Iterator iter = recipients.iterator(); iter.hasNext();) {
                RecipientInformation info = (RecipientInformation) iter.next();
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        MimeBodyPart part = SMIMEUtil
                                .toMimeBodyPart(info.getContent(keyHolder.getPrivateKey(), "BC"));
                        // strippedMessage contains the decrypted message.
                        strippedMessage = part;
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList list = new ArrayList(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.apache.james.transport.mailets.SMIMEDecrypt.java

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 *///from  w  w  w. j  a va  2  s.com
@SuppressWarnings("unchecked")
public void service(Mail mail) throws MessagingException {
    MimeMessage message = mail.getMessage();
    Part strippedMessage = null;
    log("Starting message decryption..");
    if (message.isMimeType("application/x-pkcs7-mime") || message.isMimeType("application/pkcs7-mime")) {
        try {
            SMIMEEnveloped env = new SMIMEEnveloped(message);
            RecipientInformationStore informationStore = env.getRecipientInfos();
            Collection<RecipientInformation> recipients = informationStore.getRecipients();
            for (RecipientInformation info : recipients) {
                RecipientId id = info.getRID();
                if (id.match(keyHolder.getCertificate())) {
                    try {
                        JceKeyTransEnvelopedRecipient recipient = new JceKeyTransEnvelopedRecipient(
                                keyHolder.getPrivateKey());
                        // strippedMessage contains the decrypted message.
                        strippedMessage = SMIMEUtil.toMimeBodyPart(info.getContent(recipient));
                        log("Encrypted message decrypted");
                    } catch (Exception e) {
                        throw new MessagingException("Error during the decryption of the message", e);
                    }
                } else {
                    log("Found an encrypted message but it isn't encrypted for the supplied key");
                }
            }
        } catch (CMSException e) {
            throw new MessagingException("Error during the decryption of the message", e);
        }
    }

    // if the decryption has been successful..
    if (strippedMessage != null) {
        // I put the private key's public certificate as a mailattribute.
        // I create a list of certificate because I want to minic the
        // behavior of the SMIMEVerifySignature mailet. In that way
        // it is possible to reuse the same matchers to analyze
        // the result of the operation.
        ArrayList<X509Certificate> list = new ArrayList<X509Certificate>(1);
        list.add(keyHolder.getCertificate());
        mail.setAttribute(mailAttribute, list);

        // I start the message stripping.
        try {
            MimeMessage newmex = new MimeMessage(message);
            Object obj = strippedMessage.getContent();
            if (obj instanceof Multipart) {
                log("The message is multipart, content type " + ((Multipart) obj).getContentType());
                newmex.setContent((Multipart) obj);
            } else {
                newmex.setContent(obj, strippedMessage.getContentType());
                newmex.setDisposition(null);
            }
            newmex.saveChanges();
            mail.setMessage(newmex);
        } catch (IOException e) {
            log("Error during the strip of the encrypted message");
            throw new MessagingException("Error during the stripping of the encrypted message", e);
        }
    }
}

From source file:org.mailster.core.crypto.smime.SmimeUtilities.java

License:Open Source License

/**
 * Try to decrypt the provided envelope with the provided certificate 
 * and private key. /*from  w w w  .j ava  2 s.c  om*/
 */
public static MimeBodyPart decryptEnvelope(SMIMEEnveloped enveloped, Key key, X509Certificate cert)
        throws Exception {
    // look for our recipient identifier
    RecipientId recId = new RecipientId();
    recId.setSerialNumber(cert.getSerialNumber());
    recId.setIssuer(cert.getIssuerX500Principal().getEncoded());

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

    // decryption step
    if (recipient != null)
        return SMIMEUtil.toMimeBodyPart(recipient.getContent(key, "BC"));
    else
        return null;
}