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

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

Introduction

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

Prototype

public SMIMEEnveloped(MimeMessage message) throws MessagingException, CMSException 

Source Link

Usage

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

License:Open Source License

/**
 * Decrypts a S/MIME encrypted MIME body part and yields a new MIME body
 * part.//from w w  w . j ava  2 s  .c om
 * 
 * @param mimeBodyPart
 *            The encrypted {@link MimeBodyPart} to be decrypted.
 * @param smimeKey
 *            The {@link SmimeKey} used to obtain the {@link PrivateKey} to
 *            decrypt the encrypted body part with.
 * @return The new S/MIME decrypted {@link MimeBodyPart}.
 */
public static MimeBodyPart decrypt(MimeBodyPart mimeBodyPart, SmimeKey smimeKey) {
    try {
        return SMIMEUtil.toMimeBodyPart(decryptContent(new SMIMEEnveloped(mimeBodyPart), smimeKey));
    } catch (Exception e) {
        throw handledException(e);
    }

}

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

License:Apache License

/**
 * @see org.apache.mailet.Mailet#service(org.apache.mailet.Mail)
 */// www  . ja  v 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)
 *///w  w  w  . j  a va2 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);
            @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;// w  w w  .  j  a va2  s .  co  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)
 */// w w w .  j  av a 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

public static MimeBodyPart decryptMimeBodyPart(MimeBodyPart mbp, KeyStore ks, char[] password)
        throws Exception {
    SMIMEEnveloped enveloped = new SMIMEEnveloped(mbp);
    Enumeration<String> aliases = ks.aliases();

    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) {
            MimeBodyPart decrypted = decryptEnvelope(enveloped, ks.getKey(alias, password),
                    (X509Certificate) ks.getCertificate(alias));
            if (decrypted != null)
                return decrypted;
        }/*w w w .java  2  s .  c  om*/
    }

    return null;
}

From source file:org.openhealthtools.openatna.net.MailConnection.java

License:Apache License

public MimeBodyPart decryptMessage(Message message) throws MessagingException {

    try {/*from   w  ww.ja va 2  s  . c  om*/
        /* Add BC */
        Security.addProvider(new BouncyCastleProvider());
        // Open the key store
        KeyStore ks = KeyStore.getInstance("PKCS12", "BC");
        ks.load(new FileInputStream(getSenderKeystoreFile()), getSenderKeystorePassword().toCharArray());

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

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

        SMIMEEnveloped m = new SMIMEEnveloped((MimeMessage) message);
        RecipientInformationStore recipients = m.getRecipientInfos();
        // TODO figure out why this doesn't work...
        //RecipientInformation        recipient = recipients.get(recId);
        RecipientInformation recipient = (RecipientInformation) recipients.getRecipients().iterator().next();

        Key key = ks.getKey(getSenderKeyAlias(), getSenderKeystorePassword().toCharArray());
        byte[] byteContent = recipient.getContent(key, "BC");
        MimeBodyPart res = SMIMEUtil.toMimeBodyPart(byteContent);
        return res;

    } catch (Exception e) {
        log.error("Problem decrypting message: ", e);
        throw new MessagingException(e.getMessage());
    }
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * Method to decrypt files attached to SMIME (not signed) messages
 *//*from  ww w . java2 s  .  c  o m*/
public byte[] decryptMessage(byte[] encryptedFile) throws Exception {
    MimeMessage msg = new MimeMessage(ContextVS.MAIL_SESSION, new ByteArrayInputStream(encryptedFile));
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = recipients.get(recipientId);
    RecipientId messageRecipientId = null;
    if (recipientInfo != null && recipientInfo.getRID() != null) {
        messageRecipientId = recipientInfo.getRID();
        log.info("messageRecipientId.getSerialNumber(): " + messageRecipientId.getSerialNumber());
    } else
        throw new ExceptionVS("No message found for recipientId: " + recipientId.getSerialNumber());
    MimeBodyPart mimeMessage = SMIMEUtil.toMimeBodyPart(recipientInfo.getContent(recipient));
    /*ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mimeMessage.writeTo(baos)
    log.info(" mimeMessage: ${new String(baos.toByteArray())}")*/
    Object messageContent = mimeMessage.getContent();
    byte[] messageContentBytes = null;
    //log.info(" messageContent class: ${messageContent?.getClass()}")
    if (messageContent instanceof MimeMultipart) {
        MimeMultipart mimeMultipart = (MimeMultipart) messageContent;
        BodyPart bodyPart = mimeMultipart.getBodyPart(0);
        InputStream stream = bodyPart.getInputStream();
        ByteArrayOutputStream bodyPartOutputStream = new ByteArrayOutputStream();
        byte[] buf = new byte[2048];
        int len;
        while ((len = stream.read(buf)) > 0) {
            bodyPartOutputStream.write(buf, 0, len);
        }
        stream.close();
        bodyPartOutputStream.close();
        messageContentBytes = bodyPartOutputStream.toByteArray();
    } else if (messageContent instanceof byte[]) {
        messageContentBytes = (byte[]) messageContent;
    } else if (messageContent instanceof String) {
        //log.info(" messageContent: ${messageContent}")
        String[] votingHeaders = mimeMessage.getHeader("votingSystemMessageType");
        String encodedContentType = null;
        if (votingHeaders != null && votingHeaders.length > 0)
            encodedContentType = mimeMessage.getHeader("votingSystemMessageType")[0];
        if (encodedContentType != null) {
            if (ContextVS.BASE64_ENCODED_CONTENT_TYPE.equals(encodedContentType)) {
                messageContentBytes = Base64.getDecoder().decode((String) messageContent);
            } else
                log.log(Level.SEVERE, "### unknown  votingSystemMessageType: " + encodedContentType);
        } else
            messageContentBytes = messageContent.toString().getBytes();
    }
    return messageContentBytes;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * Method to decrypt SMIME signed messages
 *//*  w w  w  . ja  va  2  s.  co  m*/
public ResponseVS decryptSMIME(byte[] encryptedMessageBytes) throws Exception {
    SMIMEMessage smimeMessageReq = null;
    MimeMessage msg = new MimeMessage(ContextVS.MAIL_SESSION, new ByteArrayInputStream(encryptedMessageBytes));
    //String encryptedMessageBytesStr = new String(encryptedMessageBytes);
    //log.info("- decryptSMIME - encryptedMessageBytesStr: " + encryptedMessageBytesStr)
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = recipients.get(recipientId);
    /*RecipientId recipientRID = null;
    if(recipient.getRID() != null) {
    recipientRID = recipient.getRID();
    log.info(" -- recipientRID.getSerialNumber(): " + recipientRID.getSerialNumber());
    if(recipient.getRID().getCertificate() != null) {
       log.info(" -- recipient: " + recipient.getRID().getCertificate().getSubjectDN().toString());
    } else log.info(" -- recipient.getRID().getCertificate() NULL");
    } else log.info(" -- getRID NULL");
    MimeBodyPart res = SMIMEUtil.toMimeBodyPart(
     recipient.getContent(new JceKeyTransEnvelopedRecipient(serverPrivateKey).setProvider("BC")));*/
    if (recipientInfo == null) {
        log.log(Level.SEVERE, "Expected recipientId.getSerialNumber(): " + recipientId.getSerialNumber());
        Collection<RecipientInformation> recipientCollection = recipients.getRecipients();
        for (RecipientInformation recipientInf : recipientCollection) {
            log.log(Level.SEVERE, "Encrypted document recipientId.getSerialNumber(): "
                    + recipientInf.getRID().getSerialNumber());
        }
        return new ResponseVS(ResponseVS.SC_ERROR_REQUEST, ContextVS.getMessage("encryptionRecipientErrorMsg"));
    }
    byte[] messageContentBytes = recipientInfo.getContent(recipient);
    //log.info(" ------- Message Contents: ${new String(messageContentBytes)}");
    smimeMessageReq = new SMIMEMessage(new ByteArrayInputStream(messageContentBytes));
    ResponseVS responseVS = new ResponseVS(ResponseVS.SC_OK);
    responseVS.setSMIME(smimeMessageReq);
    return responseVS;
}

From source file:org.votingsystem.signature.util.Encryptor.java

License:Open Source License

/**
 * helper method to decrypt SMIME signed messages
 *//*from w  w  w .  j  a  va 2  s  .  co m*/
public static byte[] decryptMessage(byte[] encryptedMessageBytes, PrivateKey receiverPrivateKey)
        throws Exception {
    log.info("decryptMessage(...) ");
    RecipientId recId = null;
    /*if(receiverCert != null) recId = new JceKeyTransRecipientId(receiverCert);*/
    Recipient recipient = new JceKeyTransEnvelopedRecipient(receiverPrivateKey).setProvider(ContextVS.PROVIDER);
    MimeMessage msg = new MimeMessage(null, new ByteArrayInputStream(encryptedMessageBytes));
    SMIMEEnveloped smimeEnveloped = new SMIMEEnveloped(msg);
    RecipientInformationStore recipients = smimeEnveloped.getRecipientInfos();
    RecipientInformation recipientInfo = null;
    //if(recId != null) recipientInfo = recipients.get(recId);
    if (recipientInfo == null && recipients.getRecipients().size() == 1) {
        recipientInfo = (RecipientInformation) recipients.getRecipients().iterator().next();
    }
    byte[] messageBytes = recipientInfo.getContent(recipient);
    return messageBytes;
}