Example usage for org.bouncycastle.mail.smime SMIMESigned getContent

List of usage examples for org.bouncycastle.mail.smime SMIMESigned getContent

Introduction

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

Prototype

public MimeBodyPart getContent() 

Source Link

Document

return the content that was signed.

Usage

From source file:chapter9.EnvelopedSignedMailExample.java

/**
 *
 * @param args//from  ww w . j a  v a2s .  c  o 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);

    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.SignedMailExample.java

/**
 *
 * @param args/*from w w w  .  j a v 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 multiPart = createMultipartWithSignature(key, cert, certsAndCRLs, dataPart);

    //3.- Create the mail message
    MimeMessage mail = Utils.createMimeMessage("example signed message", multiPart, multiPart.getContentType());

    //4.- Extract the message from the mail message
    if (mail.isMimeType("multipart/signed")) {
        SMIMESigned signed = new SMIMESigned((MimeMultipart) mail.getContent());

        //5.- 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!!");

        //6.- 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:com.cordys.coe.test.smime.TestSMIMEBouncyCastle.java

License:Apache License

/**
 * DOCUMENTME./*from   w w w.  j  av a2  s  .com*/
 *
 * @param   res
 *
 * @throws  Exception  DOCUMENTME
 */
private void doSignatureValidation(MimeBodyPart res) throws Exception {
    if (res.isMimeType("multipart/signed")) {
        SMIMESigned s = new SMIMESigned((MimeMultipart) res.getContent());

        //
        // extract the content
        //
        MimeBodyPart content = s.getContent();

        System.out.println("Content:");

        Object cont = content.getContent();

        if (cont instanceof String) {
            System.out.println((String) cont);
        } else if (cont instanceof Multipart) {
            System.out.println(MailMessageUtil.dumpMultipart("", (Multipart) cont));
        }

        System.out.println("Status:");

        verify(s);
    } else if (res.isMimeType("application/pkcs7-mime") || res.isMimeType("application/x-pkcs7-mime")) {
        //
        // in this case the content is wrapped in the signature block.
        //
        SMIMESigned s = new SMIMESigned(res);

        //
        // extract the content
        //
        MimeBodyPart content = s.getContent();

        System.out.println("Content:");

        Object cont = content.getContent();

        if (cont instanceof String) {
            System.out.println((String) cont);
        } else if (cont instanceof Multipart) {
            System.out.println(MailMessageUtil.dumpMultipart("", (Multipart) cont));
        }

        System.out.println("Status:");

        verify(s);
    } else {
        System.err.println("Not a signed message!");
    }
}

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

/**
 * @param mp/* ww  w.  j  a v  a  2s.c o m*/
 * @param certs
 * @param cte
 * @return
 * @throws MessagingException
 * @throws GeneralSecurityException
 * @throws IOException
 * @throws CertificateEncodingException
 */
public static Tuple verifySmimeDigSig(Multipart mp, Certificate[] certs, String cte)
        throws MessagingException, GeneralSecurityException, IOException, CertificateEncodingException {

    tstArgIsType("multipart", mp, MimeMultipart.class);
    tstObjArg("certs", certs);

    MimeMultipart mmp = (MimeMultipart) mp;
    SMIMESigned sc;
    SignerInformation si;
    byte[] digest = null;

    try {
        sc = isEmpty(cte) ? new SMIMESigned(mmp) : new SMIMESigned(mmp, cte);
    } catch (CMSException e) {
        throw new GeneralSecurityException(e);
    }

    Provider prov = Crypto.getInstance().getProvider();
    Store s = new JcaCertStore(asList(true, certs));
    Collection<?> c;
    JcaSimpleSignerInfoVerifierBuilder bdr;
    for (Object obj : sc.getSignerInfos().getSigners())
        try {
            si = (SignerInformation) obj;
            c = s.getMatches(si.getSID());
            for (Iterator<?> it = c.iterator(); it.hasNext();) {
                bdr = new JcaSimpleSignerInfoVerifierBuilder().setProvider(prov);
                if (si.verify(bdr.build((X509CertificateHolder) it.next()))) {
                    digest = si.getContentDigest();
                    break;
                }
            }
            if (digest != null) {
                break;
            }
        } catch (Exception e) {
        }

    if (digest == null) {
        throw new GeneralSecurityException("Failed to verify signature: no matching certificate");
    }
    //else
    return new Tuple(sc.getContentAsMimeMessage(newSession()).getContent(), digest);
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Verifies a signature against the passed certificate
 *
 * @param contentTransferEncoding one of 7bit quoted-printable base64 8bit
 * binary//from  w w  w .  j  av a2s. c  om
 */
public MimeBodyPart verify(Part part, String contentTransferEncoding, Certificate cert) throws Exception {
    if (part == null) {
        throw new GeneralSecurityException("Signature verification failed: Mime part is absent");
    }
    if (part.isMimeType("multipart/signed")) {
        MimeMultipart signedMultiPart = (MimeMultipart) part.getContent();
        //possible encoding: 7bit quoted-printable base64 8bit binary
        SMIMESigned signed = null;
        if (contentTransferEncoding == null) {
            //the default encoding in BC is 7bit but the default content transfer encoding in AS2 is binary.
            signed = new SMIMESigned(signedMultiPart, "binary");
        } else {
            signed = new SMIMESigned(signedMultiPart, contentTransferEncoding);
        }
        X509Certificate x509Cert = this.castCertificate(cert);
        X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
        SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                .build(certHolder);
        SignerInformationStore signerStore = signed.getSignerInfos();
        Iterator<SignerInformation> iterator = signerStore.getSigners().iterator();
        while (iterator.hasNext()) {
            SignerInformation signerInfo = iterator.next();
            if (!signerInfo.verify(verifier)) {
                StringBuilder signatureCertInfo = new StringBuilder();
                //try to gain more information about the problem
                if (signerInfo.getSID() != null) {
                    if (signerInfo.getSID().getSerialNumber() != null) {
                        signatureCertInfo.append("Serial number (DEC): ");
                        signatureCertInfo.append(signerInfo.getSID().getSerialNumber());
                    }
                    if (signerInfo.getSID().getIssuer() != null) {
                        if (signatureCertInfo.length() > 0) {
                            signatureCertInfo.append("\n");
                        }
                        signatureCertInfo.append("Issuer: ");
                        signatureCertInfo.append(signerInfo.getSID().getIssuer().toString());
                    }
                }
                if (signatureCertInfo.length() > 0) {
                    signatureCertInfo.insert(0, "Signature certificate information:\n");
                }
                StringBuilder checkCertInfo = new StringBuilder();
                KeystoreCertificate certificate = new KeystoreCertificate();
                certificate.setCertificate(x509Cert);
                checkCertInfo.append("Verification certificate information:\n");
                checkCertInfo.append("Serial number (DEC): ");
                checkCertInfo.append(certificate.getSerialNumberDEC());
                checkCertInfo.append("\n");
                checkCertInfo.append("Serial number (HEX): ");
                checkCertInfo.append(certificate.getSerialNumberHEX());
                checkCertInfo.append("\n");
                checkCertInfo.append("Finger print (SHA-1): ");
                checkCertInfo.append(certificate.getFingerPrintSHA1());
                checkCertInfo.append("\n");
                checkCertInfo.append("Valid from: ");
                checkCertInfo.append(
                        DateFormat.getDateInstance(DateFormat.SHORT).format(certificate.getNotBefore()));
                checkCertInfo.append("\n");
                checkCertInfo.append("Valid to: ");
                checkCertInfo
                        .append(DateFormat.getDateInstance(DateFormat.SHORT).format(certificate.getNotAfter()));
                checkCertInfo.append("\n");
                checkCertInfo.append("Issuer: ");
                checkCertInfo.append(x509Cert.getIssuerX500Principal().toString());
                StringBuilder message = new StringBuilder("Verification failed");
                message.append("\n\n");
                message.append(signatureCertInfo);
                message.append("\n\n");
                message.append(checkCertInfo);
                throw new SignatureException(message.toString());
            }
        }
        return signed.getContent();
    } else {
        throw new GeneralSecurityException("Content-Type indicates data isn't signed");
    }
}

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

License:Open Source License

@Test
public void testSignedAS2Message() throws Exception {
    InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG);
    ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins));

    partnershipDVO.setIsOutboundSignRequired(true);
    String mid = RANDOM.toString();

    AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID
            "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG));

    //Verify As2Signing Message
    try {/*from  w w w .  jav  a  2 s. c om*/
        SMIMESigned signed = new SMIMESigned((MimeMultipart) as2Msg.getBodyPart().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.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 {//from w w  w  . java  2s .  c om
        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.edi.as2.module.test.OutgoingMessageProcessorTest.java

License:Open Source License

@Test
public void testSignedCommpressMessage() throws Exception {
    InputStream ins = FIXTURE_LOADER.getResourceAsStream(MOCK_AS2_MSG);
    ByteArrayInputStream bIns = new ByteArrayInputStream(IOHandler.readBytes(ins));

    // Prepare Data
    String mid = RANDOM.toString();
    partnershipDVO.setIsOutboundSignRequired(true);
    partnershipDVO.setIsOutboundCompressRequired(true);
    //Process message
    AS2Message as2Msg = TARGET.storeOutgoingMessage(mid, //MessageID
            "xml", partnershipDVO, new InputStreamDataSource(bIns, "xml", MOCK_AS2_MSG));

    try {/*  w  w w.j  a v a2 s .  com*/
        //Verify Message Signature
        SMIMESigned signed = new SMIMESigned((MimeMultipart) as2Msg.getBodyPart().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");
            }
        }

        // Verify MIC Value
        MimeBodyPart signedPart = signed.getContent();
        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());

        //Decompress Message
        SMIMECompressed compressed = new SMIMECompressed(signedPart);
        MimeBodyPart decompressedPart = SMIMEUtil.toMimeBodyPart(compressed.getContent());

        //Assert the filename value
        String filenameHdr = decompressedPart.getHeader("Content-Disposition")[0];
        Assert.assertEquals("Lost Filename Header Information", MOCK_AS2_MSG, getFileName(filenameHdr));

    } catch (Exception exp) {
        Assert.fail("Signature Verfifcation Failed");
    }

}

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

License:Open Source License

/**
 * Unsigns the encapsulated MIME body part.
 * /*  w  w w.  j  a  v a 2s  .  c  o m*/
 * @return the an S/MIME message encapsulating the signed content.
 * @throws SMimeException if unable to unsign the body part.
 */
public SMimeMessage unsign() throws SMimeException {
    try {
        setDefaults();

        SMIMESigned signed = new SMIMESigned((MimeMultipart) bodyPart.getContent());
        MimeBodyPart signedPart = signed.getContent();
        if (signedPart == null) {
            throw new SMimeException("No signed part");
        }
        return new SMimeMessage(signedPart, this);
    } catch (Exception e) {
        if (e instanceof CMSException) {
            e = ((CMSException) e).getUnderlyingException();
        }
        throw new SMimeException("Unable to unsign body part", e);
    }
}

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

License:Open Source License

/**
 * Verifies the encapsulated MIME body part.
 * //from ww  w.j a v  a  2 s  . c  o  m
 * @param cert the certificate for verification.
 * @return an S/MIME message encapsulating the signed content. 
 * @throws SMimeException if unable to verify the body part.
 */
public SMimeMessage verify(X509Certificate cert) throws SMimeException {
    try {
        if (cert == null) {
            throw new SMimeException("No certificate for verification");
        }

        setDefaults();

        SMIMESigned signed = new SMIMESigned((MimeMultipart) bodyPart.getContent());
        // CertStore cs = signed.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = signed.getSignerInfos();
        Iterator signerInfos = signers.getSigners().iterator();

        while (signerInfos.hasNext()) {
            SignerInformation signerInfo = (SignerInformation) signerInfos.next();
            if (!signerInfo.verify(cert, "BC")) {
                throw new SMimeException("Verification failed");
            }
        }

        MimeBodyPart signedPart = signed.getContent();
        if (signedPart == null) {
            throw new SMimeException("Unable to extract signed part");
        } else {
            return new SMimeMessage(signedPart, this);
        }
    } catch (Exception e) {
        if (e instanceof CMSException) {
            e = ((CMSException) e).getUnderlyingException();
        }
        throw new SMimeException("Unable to verify body part", e);
    }
}