Example usage for org.bouncycastle.mail.smime SMIMEEnvelopedGenerator DES_EDE3_CBC

List of usage examples for org.bouncycastle.mail.smime SMIMEEnvelopedGenerator DES_EDE3_CBC

Introduction

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

Prototype

String DES_EDE3_CBC

To view the source code for org.bouncycastle.mail.smime SMIMEEnvelopedGenerator DES_EDE3_CBC.

Click Source Link

Usage

From source file:com.cordys.coe.ac.emailio.outbound.EmailMessageFactory.java

License:Apache License

/**
 * This method encrypt the given email using the public keys for all senders.
 *
 * @param   lMessages         The list to add all individual messages to.
 * @param   mmMessage         The message to encrypt.
 * @param   eicConfiguration  The configuration of the connector.
 * @param   sSession          The JavaMail session to use.
 *
 * @throws  OutboundEmailException  In case of any exceptions.
 *///  ww  w.ja v  a  2 s  .  c om
private static void encryptMessage(List<MimeMessage> lMessages, MimeMessage mmMessage,
        ISMIMEConfiguration eicConfiguration, Session sSession) throws OutboundEmailException {
    // Create the encrypter object
    SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();

    try {
        // Add the public keys of all receivers to the encrypter.
        Address[] aaAdresses = mmMessage.getAllRecipients();

        for (Address address : aaAdresses) {
            InternetAddress ia = (InternetAddress) address;

            // Find the public key for the given email address.
            ICertificateInfo ciRecipient = eicConfiguration.getCertificateInfo(ia.getAddress());

            if ((ciRecipient == null) && !eicConfiguration.getBypassSMIME()) {
                throw new OutboundEmailException(
                        OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_THE_PUBLIC_KEY_FOR_THE_EMAIL_ADDRESS_0,
                        ia.toString());
            }

            if (ciRecipient != null) {
                encrypter.addKeyTransRecipient(ciRecipient.getX509Certificate());
            } else {
                // Now we could have a funny situation. The following might happen: a mail has
                // to send to 3 recipients. 1 has no certificate and the bypasssmime is enabled.
                // What to do now? We need to create a new version of the mail in plain text and
                // remove all recipients except this one. NOTE: We cannot avoid the recipient
                // getting 2 mails: 1 unreadable version and 1 plain one. This is beacuse we
                // cannot remove the recipient from the original message because that message
                // has been signed.
                if (eicConfiguration.getBypassSMIME()) {
                    if (LOG.isDebugEnabled()) {
                        LOG.debug(
                                "BypassSMIME is enabled, so going to send a plain text version for user " + ia);
                    }

                    MimeMessage mmPlain = new MimeMessage(mmMessage);
                    mmPlain.setRecipient(RecipientType.TO, ia);
                    mmPlain.saveChanges();
                    lMessages.add(mmPlain);
                } else {
                    // We need to throw an error since we cannot encrypt to all users.
                    throw new OutboundEmailException(
                            OutboundEmailExceptionMessages.OEE_COULD_NOT_FIND_A_CERTIFICATE_FOR_RECIPIENT_0,
                            ia.toString());
                }
            }
        }

        // Encrypt the message
        MimeBodyPart encryptedPart = encrypter.generate(mmMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC");

        // Create a new MimeMessage that contains the encrypted and signed content
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encryptedPart.writeTo(out);

        MimeMessage encryptedMessage = new MimeMessage(sSession, new ByteArrayInputStream(out.toByteArray()));

        // Set all original MIME headers in the encrypted message
        Enumeration<?> headers = mmMessage.getAllHeaderLines();

        while (headers.hasMoreElements()) {
            String headerLine = (String) headers.nextElement();

            // Make sure not to override any content-* headers from the original message
            if (!Strings.toLowerCase(headerLine).startsWith("content-")) {
                encryptedMessage.addHeaderLine(headerLine);
            }
        }

        // Add the encrypted message to the list so that it will be sent.
        lMessages.add(encryptedMessage);
    } catch (Exception e) {
        throw new OutboundEmailException(e, OutboundEmailExceptionMessages.OEE_ERROR_ENCRYPTING_THE_MAIL);
    }
}

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

License:Apache License

/**
 * This method sends the message to the receiver.
 *
 * @throws  Exception  DOCUMENTME/*from   w  w w  .  j  av a 2s .  c om*/
 */
private void sendMessage() throws Exception {
    final InternetAddress[] RECEIVER_ADDRESS = new InternetAddress[] {
            new InternetAddress("outlook2007@ces70.cordys.com", "Outlook 2007 User"),
            new InternetAddress("outlookexpress@ces70.cordys.com", "Outlook Express User"),
            new InternetAddress("thunderbird@ces70.cordys.com", "Thunderbird User"),
            new InternetAddress("cordystestuser1@ces70.cordys.com", "Cordys Test User 1"),
            new InternetAddress("cordystestuser2@ces70.cordys.com", "Cordys Test User 2") };
    final InternetAddress SENDER_ADDRESS = new InternetAddress("testprogram@ces70.cordys.com",
            "Test Program User");
    String sSubject = "From test progam V1 [S&E] No r";
    boolean bDoEncryption = true;
    // String sContent = "Single line"+System.getProperty("line.separator")+"SecondLine";
    String sContent = "Single line\nSecondLine";

    // Add capabilities.
    MailcapCommandMap mailcap = (MailcapCommandMap) CommandMap.getDefaultCommandMap();

    mailcap.addMailcap(
            "application/pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_signature");
    mailcap.addMailcap(
            "application/pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.pkcs7_mime");
    mailcap.addMailcap(
            "application/x-pkcs7-signature;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_signature");
    mailcap.addMailcap(
            "application/x-pkcs7-mime;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.x_pkcs7_mime");
    mailcap.addMailcap(
            "multipart/signed;; x-java-content-handler=org.bouncycastle.mail.smime.handlers.multipart_signed");

    CommandMap.setDefaultCommandMap(mailcap);

    /* Add BC */
    Security.addProvider(new BouncyCastleProvider());

    /* Get the private key to sign the message with */
    ICertificateInfo certInfo = m_km.getCertificateInfo(SENDER_ADDRESS.getAddress());

    if (certInfo == null) {
        throw new Exception("cannot find private key for email address " + SENDER_ADDRESS);
    }

    /* Create the message to sign and encrypt */
    Properties props = System.getProperties();
    props.put("mail.smtp.host", "srv-nl-ces70");

    Session session = Session.getDefaultInstance(props, null);

    MimeMessage body = new MimeMessage(session);
    body.setContent(sContent, "text/plain");
    body.saveChanges();

    /* Create the SMIMESignedGenerator */
    SMIMECapabilityVector capabilities = new SMIMECapabilityVector();
    capabilities.addCapability(SMIMECapability.dES_EDE3_CBC);
    capabilities.addCapability(SMIMECapability.rC2_CBC, 128);
    capabilities.addCapability(SMIMECapability.dES_CBC);

    X509Certificate cert = certInfo.getX509Certificate();

    ASN1EncodableVector attributes = new ASN1EncodableVector();
    X509Name name = new X509Name(cert.getIssuerDN().getName());
    IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(name, cert.getSerialNumber());
    SMIMEEncryptionKeyPreferenceAttribute encryptionKeyPreferenceAttribute = new SMIMEEncryptionKeyPreferenceAttribute(
            issuerAndSerialNumber);
    attributes.add(encryptionKeyPreferenceAttribute);
    attributes.add(new SMIMECapabilitiesAttribute(capabilities));

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.addSigner((PrivateKey) certInfo.getKey(), cert,
            "DSA".equals(certInfo.getKey().getAlgorithm()) ? SMIMESignedGenerator.DIGEST_SHA1
                    : SMIMESignedGenerator.DIGEST_MD5,
            new AttributeTable(attributes), null);

    /* Add the list of certs to the generator */
    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(cert);

    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    /* Sign the message */
    MimeMultipart mm = signer.generate(body, "BC");
    MimeMessage signedMessage = new MimeMessage(session);

    /* Set the content of the signed message */
    signedMessage.setContent(mm);
    signedMessage.saveChanges();

    /* Create the encrypter */
    if (bDoEncryption) {
        SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();

        for (InternetAddress ia : RECEIVER_ADDRESS) {
            ICertificateInfo ciTemp = m_km.getCertificateInfo(ia.getAddress());

            if (ciTemp != null) {
                encrypter.addKeyTransRecipient(ciTemp.getX509Certificate());
            } else if (LOG.isDebugEnabled()) {
                LOG.debug("No certificate found for " + ia.toString());
            }
        }

        /* Encrypt the message */
        MimeBodyPart encryptedPart = encrypter.generate(signedMessage, SMIMEEnvelopedGenerator.DES_EDE3_CBC,
                "BC");

        /*
         * Create a new MimeMessage that contains the encrypted and signed content
         */
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        encryptedPart.writeTo(out);

        body = new MimeMessage(session, new ByteArrayInputStream(out.toByteArray()));
    } else {
        body = signedMessage;
    }

    body.setFrom(SENDER_ADDRESS);
    body.setRecipients(Message.RecipientType.TO, RECEIVER_ADDRESS);
    body.addRecipient(Message.RecipientType.TO,
            new InternetAddress("intermediate@ces70.cordys.com", "Intermediate user"));

    body.setSentDate(new Date());
    body.addHeader("User-Agent", "CordysMailClient");
    body.setSubject(sSubject);

    Transport.send(body);
}

From source file:hk.hku.cecid.edi.as2.module.test.IncomingMessageProcessorTest.java

License:Open Source License

private MimeBodyPart encrypt(MimeBodyPart bodyPart) throws Exception {
    // Create Encrypter
    SMIMEEnvelopedGenerator encrypter = new SMIMEEnvelopedGenerator();
    encrypter.setContentTransferEncoding("base64");
    encrypter.addKeyTransRecipient(partnershipDVO.getEncryptX509Certificate());

    // Encrypt BodyPart
    MimeBodyPart encryptedPart = encrypter.generate(bodyPart, SMIMEEnvelopedGenerator.DES_EDE3_CBC, "BC");
    return encryptedPart;
}

From source file:krypto.KryptoService.java

License:Apache License

/**
 * Verschlsselt eine E-Mail unter Bercksichtigung der angegebenen Konfiguration. 
 * @param mail//  ww  w .  j a  v  a  2s.c o m
 * @param config
 * @param cert
 * @return
 */
public static String encryptMail(Mail mail, Config config, X509Certificate cert, String pword) {
    try {
        SMIMEEnvelopedGenerator gen = new SMIMEEnvelopedGenerator();
        gen.addKeyTransRecipient(cert);
        Properties props = new Properties();
        props.put("mail.smtp.host", "mail.java-tutor.com");
        Session session = Session.getDefaultInstance(props);
        MimeMessage body = new MimeMessage(session);

        // set Text
        MimeBodyPart msg = new MimeBodyPart();
        msg.setText(Utils.toString(mail.getText()));

        // set from
        Address fromUser = new InternetAddress(mail.getAbsender());
        body.setFrom(fromUser);

        // set to
        Address toUser = new InternetAddress(mail.getEmpfaenger());
        body.setRecipient(Message.RecipientType.TO, toUser);

        // set subject
        body.setSubject(mail.getBetreff());

        // set send date
        body.setSentDate(mail.getAbsendeDatum());

        // select algorithm
        String algorithm = SMIMEEnvelopedGenerator.AES256_CBC;
        if (config.getEncrAlg() == 1)
            algorithm = SMIMEEnvelopedGenerator.DES_EDE3_CBC;

        // apply smime
        MimeBodyPart mp = gen.generate(msg, algorithm, "BC");
        body.setContent(mp.getContent(), mp.getContentType());

        body.saveChanges();

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        body.writeTo(out);
        return MailService.removeMessageId(out.toString(Charset.defaultCharset().name()));
    } catch (MessagingException e) {
        MessageBox box = new MessageBox(new Shell(), SWT.OK | SWT.ICON_ERROR);
        box.setText(ITexte.ERR_ENCRYPT.getText(config.getSprache()));
        box.setMessage(ITexte.ERR_ENCRYPT_MAIL.getText(config.getSprache()));
        box.open();
    } catch (NoSuchAlgorithmException e) {
        MessageBox box = new MessageBox(new Shell(), SWT.OK | SWT.ICON_ERROR);
        box.setText(ITexte.ERR_ENCRYPT.getText(config.getSprache()));
        box.setMessage(ITexte.ERR_ENCRYPT_ALGORITHM.getText(config.getSprache()));
        box.open();
    } catch (NoSuchProviderException e) {
        MessageBox box = new MessageBox(new Shell(), SWT.OK | SWT.ICON_ERROR);
        box.setText(ITexte.ERR_ENCRYPT.getText(config.getSprache()));
        box.setMessage(ITexte.ERR_ENCRYPT_PROVIDER.getText(config.getSprache()));
        box.open();
    } catch (SMIMEException e) {
        MessageBox box = new MessageBox(new Shell(), SWT.OK | SWT.ICON_ERROR);
        box.setText(ITexte.ERR_ENCRYPT.getText(config.getSprache()));
        box.setMessage(ITexte.ERR_ENCRYPT_SMIME.getText(config.getSprache()));
        box.open();
    } catch (Exception e) {
        MessageBox box = new MessageBox(new Shell(), SWT.OK | SWT.ICON_ERROR);
        box.setText(ITexte.ERR_ENCRYPT.getText(config.getSprache()));
        box.setMessage(ITexte.ERR_ENCRYPT_JCE.getText(config.getSprache()));
        box.open();
    }
    return null;
}