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

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

Introduction

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

Prototype

public SignerInformationStore getSignerInfos() 

Source Link

Document

return the collection of signers that are associated with the signatures for the message.

Usage

From source file:br.ufpb.dicomflow.integrationAPI.mail.impl.SMTPServiceExtractor.java

License:Open Source License

/**
  * verify the signature (assuming the cert is contained in the message)
  *//*from w w  w.  j a  va2 s . com*/
private boolean verify(SMIMESigned s) throws Exception {
    //
    // extract the information to verify the signatures.
    //

    //
    // certificates and crls passed in the signature - this must happen before
    // s.getSignerInfos()
    //
    Store certs = s.getCertificates();

    //
    // SignerInfo blocks which contain the signatures
    //
    SignerInformationStore signers = s.getSignerInfos();

    Collection c = signers.getSigners();
    Iterator it = c.iterator();

    //
    // check each signer
    //
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = certs.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509Certificate cert = new JcaX509CertificateConverter()
                .getCertificate((X509CertificateHolder) certIt.next());

        //
        // verify that the sign is correct and that it was generated
        // when the certificate was current
        //
        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().build(cert))) {
            return true;
        } else {
            return false;
        }
    }
    return false;
}

From source file:com.cordys.coe.ac.emailio.util.smime.SMIMEUtil.java

License:Apache License

/**
 * verify the signature (assuming the cert is contained in the message).
 *
 * @param   sSigned  The signed content.
 *
 * @throws  Exception  In case of any exceptions.
 *///from w  w w. ja  va 2 s  .  c o  m
private static void verify(SMIMESigned sSigned) throws Exception {
    // Get all certificates from the mail itself
    CertStore certs = sSigned.getCertificatesAndCRLs("Collection", "BC");

    // SignerInfo blocks which contain the signatures
    SignerInformationStore signers = sSigned.getSignerInfos();

    Collection<?> c = signers.getSigners();
    Iterator<?> it = c.iterator();

    // Check each signer
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection<?> certCollection = certs.getCertificates(signer.getSID());

        Iterator<?> certIt = certCollection.iterator();
        X509Certificate cert = (X509Certificate) certIt.next();

        // Verify that the signature is correct and that it was generated
        // when the certificate was current
        if (signer.verify(cert, "BC")) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Signature for " + signer.getSID().getSubjectAsString() + " is valid.");
            }
        } else {
            throw new EmailIOException(
                    EmailIOExceptionMessages.EIOE_VALIDATION_OF_THE_SIGNATURE_FOR_CERTIFICATE_0_FAILED,
                    signer.getSID().getSubjectAsString());
        }
    }
}

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

License:Apache License

/**
 * verify the signature (assuming the cert is contained in the message).
 *
 * @param   s  DOCUMENTME/*w  w w. jav  a  2 s. co  m*/
 *
 * @throws  Exception  DOCUMENTME
 */
private static void verify(SMIMESigned s) throws Exception {
    CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
    //
    // SignerInfo blocks which contain the signatures
    //
    SignerInformationStore signers = s.getSignerInfos();

    Collection<?> c = signers.getSigners();
    Iterator<?> it = c.iterator();

    //
    // check each signer
    //
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection<?> certCollection = certs.getCertificates(signer.getSID());

        Iterator<?> certIt = certCollection.iterator();
        X509Certificate cert = (X509Certificate) certIt.next();

        //
        // verify that the sig is correct and that it was generated
        // when the certificate was current
        //
        if (signer.verify(cert, "BC")) {
            System.out.println("signature verified");
        } else {
            System.out.println("signature failed!");
        }
    }
}

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

License:Open Source License

/**
 * @param mp/*from  w  w  w .j a v a 2s  .co 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

/**
 * Returns the digest OID algorithm from a signature that signes the passed
 * message part The return value for sha1 is e.g. "1.3.14.3.2.26".
 *//*  www  . jav  a2  s  .com*/
public String getDigestAlgOIDFromSignature(Part part) throws Exception {
    if (part == null) {
        throw new GeneralSecurityException("getDigestAlgOIDFromSignature: Part is absent");
    }
    if (part.isMimeType("multipart/signed")) {
        MimeMultipart signedMultiPart = null;
        if (part.getContent() instanceof MimeMultipart) {
            signedMultiPart = (MimeMultipart) part.getContent();
        } else {
            //assuming it is an inputstream now
            signedMultiPart = new MimeMultipart(
                    new ByteArrayDataSource((InputStream) part.getContent(), part.getContentType()));
        }
        SMIMESigned signed = new SMIMESigned(signedMultiPart);
        SignerInformationStore signerStore = signed.getSignerInfos();
        Iterator iterator = signerStore.getSigners().iterator();
        while (iterator.hasNext()) {
            SignerInformation signerInfo = (SignerInformation) iterator.next();
            return (signerInfo.getDigestAlgOID());
        }
        throw new GeneralSecurityException(
                "getDigestAlgOIDFromSignature: Unable to identify signature algorithm.");
    }
    throw new GeneralSecurityException("Content-Type indicates data isn't signed");
}

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 ww .j  ava 2s  .c o  m
 */
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:eu.peppol.as2.MimeMessageHelperTest.java

License:EUPL

/**
 * verify the signature (assuming the cert is contained in the message)
 *//*from  w w  w. j av  a  2s.  com*/
private boolean verify(String resourceName, boolean debug) {

    System.out.println("Verifying resource " + resourceName + " (debug=" + debug + ")");
    String resourcePath = "real-mdn-examples/" + resourceName;

    try {

        // add provider
        Security.addProvider(new BouncyCastleProvider());

        // shortcuts lots of steps in the above test (parseLegalMimeMessageWithHeaders)
        MimeMultipart multipartSigned = (MimeMultipart) MimeMessageHelper
                .createMimeMessage(
                        MimeMessageHelperTest.class.getClassLoader().getResourceAsStream(resourcePath))
                .getContent();
        assertNotNull(multipartSigned);

        // verify signature

        SMIMESigned signedMessage = new SMIMESigned(multipartSigned);
        Store certs = signedMessage.getCertificates();

        SignerInformationStore signers = signedMessage.getSignerInfos();

        for (Object signerInformation : signers.getSigners()) {
            SignerInformation signer = (SignerInformation) signerInformation;
            Collection certCollection = certs.getMatches(signer.getSID());

            Iterator certIterator = certCollection.iterator();

            X509Certificate cert = new JcaX509CertificateConverter().setProvider(new BouncyCastleProvider())
                    .getCertificate((X509CertificateHolder) certIterator.next());

            if (debug)
                System.out.println("Signing certificate : " + cert);

            SignerInformationVerifier signerInformationVerifier = new JcaSimpleSignerInfoVerifierBuilder()
                    .setProvider(new BouncyCastleProvider()).build(cert);
            if (signer.verify(signerInformationVerifier))
                return true;

        }

    } catch (Exception ex) {
        System.out.println("Verification failed with exception " + ex.getMessage());
    }

    return false;

}

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  ww. j av  a2s.  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 {// ww  w. j av a 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.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 {/*from  w w  w  .ja v a2  s .c  o m*/
        //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");
    }

}