Example usage for org.bouncycastle.mail.smime SMIMESignedGenerator setContentTransferEncoding

List of usage examples for org.bouncycastle.mail.smime SMIMESignedGenerator setContentTransferEncoding

Introduction

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

Prototype

public void setContentTransferEncoding(String encoding) 

Source Link

Document

set the content-transfer-encoding for the CMS block (enveloped data, signature, etc...) in the message.

Usage

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

License:Open Source License

private MimeBodyPart signMessage(MimeBodyPart bodyPart) throws Exception {
    X509Certificate cert = partnershipDVO.getVerifyX509Certificate();

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

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

    SMIMESignedGenerator signer = new SMIMESignedGenerator();
    signer.setContentTransferEncoding("base64");
    signer.addSigner(keyMan.getPrivateKey(), partnershipDVO.getVerifyX509Certificate(),
            SMIMESignedGenerator.DIGEST_SHA1, new AttributeTable(attributes), null);

    // Add the list of certs to the generator
    ArrayList certList = new ArrayList();
    certList.add(cert);//from  www  . ja  v  a  2s  .c o  m
    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    signer.addCertificatesAndCRLs(certs);

    // Sign body part
    MimeMultipart mm = signer.generate(bodyPart, "BC");

    InternetHeaders headers = new InternetHeaders();
    boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true")).booleanValue();
    headers.setHeader("Content-Type",
            isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mm.writeTo(baos);
    MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

    return signedPart;
}

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

License:Open Source License

/**
 * Signs the encapsulated MIME body part.  
 * // w  ww  .  j  ava2  s.c om
 * @return an S/MIME message encapsulating the signed MIME body part. 
 * @throws SMimeException if unable to sign the body part.
 */
public SMimeMessage sign() throws SMimeException {
    try {
        if (privateKey == null) {
            throw new SMimeException("Private key not found");
        }

        try {
            setDefaults();

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

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

            SMIMESignedGenerator signer = new SMIMESignedGenerator();
            signer.setContentTransferEncoding(getContentTransferEncoding());
            signer.addSigner(privateKey, cert, getDigestAlgorithm(), new AttributeTable(attributes), null);

            /* Add the list of certs to the generator */
            ArrayList certList = new ArrayList();
            certList.add(cert);
            CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                    SECURITY_PROVIDER);
            signer.addCertificatesAndCRLs(certs);

            /* Sign the body part */
            MimeMultipart mm = signer.generate(bodyPart, SECURITY_PROVIDER);

            InternetHeaders headers = new InternetHeaders();
            boolean isContentTypeFolded = new Boolean(System.getProperty("mail.mime.foldtext", "true"))
                    .booleanValue();
            headers.setHeader("Content-Type",
                    isContentTypeFolded ? mm.getContentType() : mm.getContentType().replaceAll("\\s", " "));
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mm.writeTo(baos);
            MimeBodyPart signedPart = new MimeBodyPart(headers, baos.toByteArray());

            return new SMimeMessage(signedPart, this);
        } catch (org.bouncycastle.mail.smime.SMIMEException ex) {
            throw new SMimeException(ex.getMessage(), ex.getUnderlyingException());
        }
    } catch (Exception e) {
        throw new SMimeException("Unable to sign body part", e);
    }
}

From source file:mail.SignedMultiPart.java

License:Apache License

/**
 * Erzeugt eine signierte MIME-Nachricht
 * @param mail//from w w w  . ja  v  a2s  .  com
 * @param config
 * @return
 * @throws Exception
 */
public String createSignedMail(KeyStore store, String pword, PrivateKey key, Mail mail, Config config)
        throws Exception {

    KeyStore credentials;
    Certificate[] chain;
    CertStore certsAndCRLs;
    X509Certificate cert;
    if (store == null) {
        credentials = Utils.createCredentialsAsKeyStore(config);
        key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
        chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
        certsAndCRLs = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
        cert = (X509Certificate) chain[0];
    } else {
        credentials = store;
        if (pword == null) {
            pword = "";
        }
        //             key = (PrivateKey)credentials.getKey(Utils.END_ENTITY_ALIAS, pword.toCharArray());
        chain = credentials.getCertificateChain(config.getAliasPSE());
        certsAndCRLs = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
        cert = (X509Certificate) chain[0];
    }

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    // Behandlung Multipart/signed
    if (config.getMimeTyp() == 0) {
        // create the message we want signed
        MimeBodyPart bodyPart = new MimeBodyPart();
        bodyPart.setText(Utils.toString(mail.getText()));

        // create the signed message
        MimeMultipart multiPart = Utils.createMultipartWithSignature(key, cert, certsAndCRLs, bodyPart,
                config.getHashDescription());

        // create the mail message
        body = Utils.createMimeMessage(mail.getBetreff(), multiPart, mail.getAbsender(), mail.getEmpfaenger(),
                multiPart.getContentType());

        body.writeTo(bOut);
    } else {

        //            boolean implicit = true;
        //            SignedContent sc = new SignedContent(implicit);

        //           CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        SMIMESignedGenerator smimeGen = new SMIMESignedGenerator();

        if (config.getHash() == 0) {
            smimeGen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA1);
            //              gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        } else {
            smimeGen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_MD5);
            //              gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_MD5);
        }

        smimeGen.addCertificatesAndCRLs(certsAndCRLs);
        smimeGen.setContentTransferEncoding(config.getTranscodeDescription());

        // workaround to get the english date format
        MimeMessage message = new MimeMessage(Session.getDefaultInstance(System.getProperties()));
        message.setSentDate(mail.getAbsendeDatum());
        message.setText("");
        message.writeTo(bOut);
        String date = MailService.removeMessageId(bOut.toString());
        date = date.substring(date.indexOf("Date:"), date.indexOf('\n') - 1).substring(date.indexOf(' ') + 1);

        // create the message
        BASE64Decoder base64dec = new BASE64Decoder();
        message = new MimeMessage(Session.getDefaultInstance(System.getProperties()));
        message.setText(Charset.defaultCharset()
                .decode(ByteBuffer.wrap(base64dec.decodeBuffer(Utils.toString(mail.getText())))).toString());
        message.setHeader("Content-Transfer-Encoding", "base64");

        // sign the message
        MimeBodyPart signed = smimeGen.generateEncapsulated(message, "BC");
        signed.setHeader("From", mail.getAbsender());
        signed.setHeader("To", mail.getEmpfaenger());
        signed.setHeader("Subject", mail.getBetreff());
        signed.setHeader("Date", date);
        signed.setHeader("MIME-Version", "1.0");
        signed.setHeader("Message-ID", "12345");

        bOut.reset();
        signed.writeTo(bOut);
    }

    return bOut.toString(Charset.defaultCharset().name()).replaceAll("Content-Transfer-Encoding: 7bit",
            "Content-Transfer-Encoding: " + config.getTranscodeDescription());

}