Example usage for org.bouncycastle.cms CMSSignedDataParser CMSSignedDataParser

List of usage examples for org.bouncycastle.cms CMSSignedDataParser CMSSignedDataParser

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedDataParser CMSSignedDataParser.

Prototype

public CMSSignedDataParser(DigestCalculatorProvider digestCalculatorProvider, CMSTypedStream signedContent,
        InputStream sigData) throws CMSException 

Source Link

Document

base constructor

Usage

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

/**
 * Verifies a signature of a passed content against the passed certificate
 *///from  ww w  .java  2  s .com
public boolean verify(byte[] content, byte[] signature, Certificate cert) throws Exception {
    if (content == null) {
        throw new GeneralSecurityException("verify: Content is absent");
    }
    if (signature == null) {
        throw new GeneralSecurityException("verify: Signature is absent");
    }
    if (signature.length == 0) {
        throw new Exception("verify: Signature length is 0");
    }
    CMSTypedStream signedContent = new CMSTypedStream(new ByteArrayInputStream(content));
    CMSSignedDataParser dataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(), signedContent,
            new ByteArrayInputStream(signature));
    dataParser.getSignedContent().drain();
    SignerInformationStore signers = dataParser.getSignerInfos();
    Collection signerCollection = signers.getSigners();
    Iterator it = signerCollection.iterator();
    X509CertificateHolder certHolder = new X509CertificateHolder(cert.getEncoded());
    SignerInformationVerifier verifier = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
            .build(certHolder);
    boolean verified = false;
    while (it.hasNext()) {
        SignerInformation signerInformation = (SignerInformation) it.next();
        if (!verified) {
            verified = signerInformation.verify(verifier);
        }
        if (verified) {
            break;
        }
    }
    return (verified);
}

From source file:eu.europa.ec.markt.dss.validation102853.cades.CAdESSignature.java

License:Open Source License

@Override
public SignatureCryptographicVerification checkSignatureIntegrity() {

    if (signatureCryptographicVerification != null) {
        return signatureCryptographicVerification;
    }// w  w  w. j  a  va  2 s  .  co m
    signatureCryptographicVerification = new SignatureCryptographicVerification();
    try {

        final List<SigningCertificateValidity> signingCertificateValidityList;
        if (providedSigningCertificateToken == null) {

            // To determine the signing certificate it is necessary to browse through all candidates found before.
            final CandidatesForSigningCertificate candidatesForSigningCertificate = getCandidatesForSigningCertificate();
            signingCertificateValidityList = candidatesForSigningCertificate
                    .getSigningCertificateValidityList();
            if (signingCertificateValidityList.size() == 0) {

                signatureCryptographicVerification
                        .setErrorMessage("There is no signing certificate within the signature.");
                return signatureCryptographicVerification;
            }
        } else {

            candidatesForSigningCertificate = new CandidatesForSigningCertificate();
            final SigningCertificateValidity signingCertificateValidity = new SigningCertificateValidity(
                    providedSigningCertificateToken);
            candidatesForSigningCertificate.add(signingCertificateValidity);
            signingCertificateValidityList = candidatesForSigningCertificate
                    .getSigningCertificateValidityList();

        }
        boolean detached = cmsSignedData.getSignedContent() == null
                || cmsSignedData.getSignedContent().getContent() == null ? true : false;
        final SignerInformation signerInformationToCheck;
        if (detached) {

            if (detachedContents == null || detachedContents.size() == 0) {

                if (signingCertificateValidityList.size() > 0) {

                    candidatesForSigningCertificate
                            .setTheSigningCertificateValidity(signingCertificateValidityList.get(0));
                }
                signatureCryptographicVerification.setErrorMessage("Detached file not found!");
                return signatureCryptographicVerification;
            }
            // Recreate a SignerInformation with the content using a CMSSignedDataParser
            final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature
            final InputStream inputStream = dssDocument.openStream();
            final CMSTypedStream signedContent = new CMSTypedStream(inputStream);
            final CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
                    signedContent, cmsSignedData.getEncoded());
            sp.getSignedContent().drain(); // Closes the stream
            final SignerId sid = signerInformation.getSID();
            signerInformationToCheck = sp.getSignerInfos().get(sid);
        } else { //         if (detachedContents == null || detachedContents.size() == 0) {

            signerInformationToCheck = signerInformation;
        }
        LOG.debug("CHECK SIGNATURE VALIDITY: ");
        for (final SigningCertificateValidity signingCertificateValidity : signingCertificateValidityList) {

            try {

                // In the case where one of the mandatory attributes is missing we set already the candidate for the signing certificate.
                // see: validation.at.nqs.bdc.TestNotQualifiedBDC.test1()
                candidatesForSigningCertificate.setTheSigningCertificateValidity(signingCertificateValidity);

                final JcaSimpleSignerInfoVerifierBuilder verifier = new JcaSimpleSignerInfoVerifierBuilder();
                final CertificateToken certificateToken = signingCertificateValidity.getCertificateToken();
                final X509Certificate certificate = certificateToken.getCertificate();
                final SignerInformationVerifier signerInformationVerifier = verifier.build(certificate);
                LOG.debug(" - WITH SIGNING CERTIFICATE: " + certificateToken.getAbbreviation());
                boolean signatureIntact = signerInformationToCheck.verify(signerInformationVerifier);
                signatureCryptographicVerification.setReferenceDataFound(signatureIntact);
                signatureCryptographicVerification.setReferenceDataIntact(signatureIntact);
                signatureCryptographicVerification.setSignatureIntact(signatureIntact);
                if (signatureIntact) {
                    break;
                }
            } catch (RuntimeOperatorException e) {

                // Cest un problme de compatibilit avec Java 7. Limplmentation de la classe sun.security.rsa.RSASignature a chang entre la version 6 et 7. Bouncy castle ne
                // prend pas correctement en compte ce changement. En effet, une exception est leve par la version 7 que BC ne catch pas correctement ce qui se traduit par
                // lenvoi dune exception : org.bouncycastle.operator.RuntimeOperatorException (Bob)
                LOG.warn(e.getMessage(), e);
            } catch (CMSSignerDigestMismatchException e) {
                LOG.error(e.getMessage(), e);
                signatureCryptographicVerification.setReferenceDataFound(true);
                signatureCryptographicVerification.setReferenceDataIntact(false);
                signatureCryptographicVerification.setSignatureIntact(false);
                signatureCryptographicVerification.setErrorMessage(e.getMessage());
            } catch (OperatorCreationException e) {
                LOG.error(e.getMessage(), e);
                signatureCryptographicVerification.setErrorMessage(e.getMessage());
            } catch (CMSException e) {
                LOG.error(e.getMessage(), e);
                signatureCryptographicVerification.setErrorMessage(e.getMessage());
            } catch (IllegalArgumentException e) {
                // Can arrive when for example:
                // java.lang.IllegalArgumentException: Unknown signature type requested: RIPEMD160WITH0.4.0.127.0.7.1.1.4.1.6
                // at org.bouncycastle.operator.DefaultSignatureAlgorithmIdentifierFinder.generate(Unknown Source) ~[bcpkix-jdk15on-1.49.jar:1.49.0]
                LOG.error(e.getMessage(), e);
                signatureCryptographicVerification.setErrorMessage(e.getMessage());
            }
        }
    } catch (CMSException e) {
        LOG.error(e.getMessage(), e);
        signatureCryptographicVerification.setErrorMessage(e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        signatureCryptographicVerification.setErrorMessage(e.getMessage());
    }
    LOG.debug(" - RESULT: " + signatureCryptographicVerification.isReferenceDataFound() + "/"
            + signatureCryptographicVerification.isReferenceDataIntact() + "/"
            + signatureCryptographicVerification.isSignatureIntact());
    return signatureCryptographicVerification;
}

From source file:eu.europa.esig.dss.cades.validation.CAdESSignature.java

License:Open Source License

/**
 * This method recreates a {@code SignerInformation} with the content using
 * a {@code CMSSignedDataParser}.//from  w  w w. j a  v  a2 s. com
 *
 * @return
 * @throws CMSException
 * @throws IOException
 */
private SignerInformation recreateSignerInformation() throws CMSException, IOException {

    final DSSDocument dssDocument = detachedContents.get(0); // only one element for CAdES Signature
    final InputStream inputStream = dssDocument.openStream();
    final CMSTypedStream signedContent = new CMSTypedStream(inputStream);
    final CMSSignedDataParser cmsSignedDataParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
            signedContent, cmsSignedData.getEncoded());
    cmsSignedDataParser.getSignedContent().drain(); // Closes the stream
    final SignerId signerId = signerInformation.getSID();
    final SignerInformation signerInformationToCheck = cmsSignedDataParser.getSignerInfos().get(signerId);
    return signerInformationToCheck;
}

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java

License:Open Source License

/**
 * Verifies one individual signature element of a signed PDF document
 *
 * @param signedData The SignedData of this signature
 * @param signedContentBytes The data being signed by this signature
 * @param sigResult The signature verification result object used to express
 * signature result data.//from   ww w.j  av  a  2  s. c o m
 * @param verifyPades The value true causes verification to check for the
 * signed signature certificate signed attributes. If present, this
 * attribute is validated against the provided signature certificate in
 * signed data.
 * @throws Exception
 */
public static void verifySign(byte[] signedData, byte[] signedContentBytes, CMSSigVerifyResult sigResult,
        boolean verifyPades) throws Exception {
    InputStream is = new ByteArrayInputStream(signedContentBytes);
    CMSSignedDataParser sp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), new CMSTypedStream(is),
            signedData);
    CMSTypedStream signedContent = sp.getSignedContent();
    signedContent.drain();
    sigResult.setSignedData(signedData);

    verifyCMSSignature(sp, sigResult);
    checkTimestamps(sp, sigResult);
}