Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signatureTimeStampToken

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signatureTimeStampToken

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signatureTimeStampToken.

Prototype

ASN1ObjectIdentifier id_aa_signatureTimeStampToken

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signatureTimeStampToken.

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.16.2.14 - <a href="http://tools.ietf.org/html/rfc3126">RFC 3126</a>

Usage

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileX.java

License:Open Source License

@Override
protected SignerInformation extendCMSSignature(CMSSignedData signedData, SignerInformation si,
        SignatureParameters parameters, Document originalData) throws IOException {

    si = super.extendCMSSignature(signedData, si, parameters, originalData);

    ASN1ObjectIdentifier attributeId = null;
    ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

    switch (getExtendedValidationType()) {
    case 1:/*from   w  w w  . j a  v  a 2 s .  c o m*/
        attributeId = PKCSObjectIdentifiers.id_aa_ets_escTimeStamp;

        toTimestamp.write(si.getSignature());

        // We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5,
        // NOTE 2)
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrType().getDEREncoded());
        toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken)
                .getAttrValues().getDEREncoded());
        break;
    case 2:
        attributeId = PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp;
        break;
    default:
        throw new IllegalStateException(
                "CAdES-X Profile: Extended validation is set but no valid type (1 or 2)");
    }

    /* Those are common to Type 1 and Type 2 */
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs)
            .getAttrValues().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrType().getDEREncoded());
    toTimestamp.write(si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationRefs)
            .getAttrValues().getDEREncoded());

    @SuppressWarnings("unchecked")
    Hashtable<ASN1ObjectIdentifier, Attribute> unsignedAttrHash = si.getUnsignedAttributes().toHashtable();
    Attribute extendedTimeStamp = getTimeStampAttribute(attributeId, getSignatureTsa(), digestAlgorithm,
            toTimestamp.toByteArray());
    unsignedAttrHash.put(attributeId, extendedTimeStamp);

    return SignerInformation.replaceUnsignedAttributes(si, new AttributeTable(unsignedAttrHash));

}

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

License:Open Source License

@Override
public List<TimestampToken> getSignatureTimestamps() throws RuntimeException {
    return getTimestampList(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
            TimestampToken.TimestampType.SIGNATURE_TIMESTAMP);
}

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

License:Open Source License

@Override
public byte[] getTimestampX1Data() {
    try {//from   w  w w.j a  va 2s .c  o m
        ByteArrayOutputStream toTimestamp = new ByteArrayOutputStream();

        toTimestamp.write(signerInformation.getSignature());

        /*
         * We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5, NOTE 2
         */
        if (signerInformation.getUnsignedAttributes() != null) {
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken).getAttrType().getDEREncoded());
            toTimestamp.write(signerInformation.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken).getAttrValues().getDEREncoded());
        }

        /* Those are common to Type 1 and Type 2 */
        toTimestamp.write(getTimestampX2Data());

        return toTimestamp.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

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

License:Open Source License

@Override
public List<TimestampToken> getSignatureTimestamps() throws RuntimeException {

    if (signatureTimestamps == null) {
        signatureTimestamps = getTimestampList(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
                TimestampType.SIGNATURE_TIMESTAMP, null);
    }//from   w  ww. j  a  v  a 2s .  c om
    return signatureTimestamps;
}

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

License:Open Source License

@Override
public byte[] getTimestampX1Data(final TimestampToken timestampToken) {

    try {//from   w  w  w  .  j  a va 2s.co m
        @SuppressWarnings("resource")
        final ByteArrayOutputStream data = new ByteArrayOutputStream();

        data.write(signerInformation.getSignature());

        /*
         * We don't include the outer SEQUENCE, only the attrType and attrValues as stated by the TS 6.3.5, NOTE 2
         */
        final AttributeTable attributes = signerInformation.getUnsignedAttributes();
        if (attributes != null) {

            final Attribute attribute = attributes.get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
            if (attribute != null) {

                data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrType()));
                data.write(DSSASN1Utils.getDEREncoded(attribute.getAttrValues()));
            }
        }

        /* Those are common to Type 1 and Type 2 */
        data.write(getTimestampX2Data(timestampToken));

        return data.toByteArray();
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
}

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

License:Open Source License

public boolean isDataForSignatureLevelPresent(final SignatureLevel signatureLevel) {

    /**/*  w  ww  .ja v  a  2s  . co m*/
     * This list contains the detail information collected during the check. It is reset for each call.
     */
    info = new ArrayList<String>();

    final AttributeTable unsignedAttributes = getUnsignedAttributes(signerInformation);
    final AttributeTable signedAttributes = getSignedAttributes(signerInformation);
    boolean dataForProfilePresent = true;
    switch (signatureLevel) {
    case CAdES_BASELINE_LTA:
        dataForProfilePresent = unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV3) != null;
        // break omitted purposely
    case CAdES_101733_A:
        if (signatureLevel != SignatureLevel.CAdES_BASELINE_LTA) {
            dataForProfilePresent &= unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV2) != null;
        }
        // break omitted purposely
    case CAdES_BASELINE_LT:
        final Store certificateStore = cmsSignedData.getCertificates();
        final Store crlStore = cmsSignedData.getCRLs();
        final Store ocspStore = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
        final Store ocspBasicStore = cmsSignedData
                .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
        final int certificateStoreSize = certificateStore.getMatches(null).size();
        final int crlStoreSize = crlStore.getMatches(null).size();
        info.add("CRL founds: " + crlStoreSize);
        final int ocspStoreSize = ocspStore.getMatches(null).size();
        info.add("OCSP founds: " + ocspStoreSize);
        final int basicOcspStoreSize = ocspBasicStore.getMatches(null).size();
        info.add("BasicOCSP founds: " + basicOcspStoreSize);
        final int ltInfoSize = crlStoreSize + ocspStoreSize + basicOcspStoreSize;
        dataForProfilePresent &= (ltInfoSize > 0);
        // break omitted purposely
    case CAdES_101733_X:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= (unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp) != null
                    || unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp) != null);
        }
        // break omitted purposely
    case CAdES_101733_C:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) != null;
            dataForProfilePresent &= isDataForSignatureLevelPresent(SignatureLevel.CAdES_BASELINE_T);
        }
        // break omitted purposely
    case CAdES_BASELINE_T:
        dataForProfilePresent &= unsignedAttributes
                .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) != null;
        // break omitted purposely
    case CAdES_BASELINE_B:
        dataForProfilePresent &= ((signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificate) != null)
                || (signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) != null));
        break; // break placed purposely
    case CMS:
        dataForProfilePresent = true;
        break;
    default:
        throw new IllegalArgumentException("Unknown level " + signatureLevel);
    }
    return dataForProfilePresent;
}

From source file:eu.europa.esig.dss.cades.signature.CAdESLevelBaselineT.java

License:Open Source License

private AttributeTable addSignatureTimestampAttribute(SignerInformation signerInformation,
        AttributeTable unsignedAttributes, CAdESSignatureParameters parameters) {
    ASN1Object signatureTimeStamp = getTimeStampAttributeValue(signatureTsa, signerInformation.getSignature(),
            parameters);/*from  w w w  . java 2  s  .com*/
    return unsignedAttributes.add(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, signatureTimeStamp);
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

License:Open Source License

private static CMSSignedData addTimestamp(String tsaUrl, CMSSignedData signedData) throws IOException {

    Collection<SignerInformation> signerInfos = signedData.getSignerInfos().getSigners();

    // get signature of first signer (should be the only one)
    SignerInformation si = signerInfos.iterator().next();
    byte[] signature = si.getSignature();

    // send request to TSA
    byte[] token = TimeStampingClient.getTimeStampToken(tsaUrl, signature, DigestType.SHA1);

    // create new SignerInformation with TS attribute
    Attribute tokenAttr = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
            new DERSet(ASN1Primitive.fromByteArray(token)));
    ASN1EncodableVector timestampVector = new ASN1EncodableVector();
    timestampVector.add(tokenAttr);/*www  .  j ava 2 s .  com*/
    AttributeTable at = new AttributeTable(timestampVector);
    si = SignerInformation.replaceUnsignedAttributes(si, at);
    signerInfos.clear();
    signerInfos.add(si);
    SignerInformationStore newSignerStore = new SignerInformationStore(signerInfos);

    // create new signed data
    CMSSignedData newSignedData = CMSSignedData.replaceSigners(signedData, newSignerStore);
    return newSignedData;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESChecker.java

License:Open Source License

/**
 * Validation is done only on digital signatures with a single signer. Valid
 * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
 * OID Data 1.2.840.113549.1.7.1//w  w  w  .  j a v  a 2 s.  co m
 *
 * @param content Is only necessary to inform if the PKCS7 package is NOT
 *        ATTACHED type. If it is of type attached, this parameter will be
 *        replaced by the contents of the PKCS7 package.
 * @param signedData Value in bytes of the PKCS7 package, such as the
 *        contents of a ".p7s" file. It is not only signature as in the
 *        case of PKCS1.
 */
// TODO: Implementar validao de co-assinaturas

public boolean check(byte[] content, byte[] signedData) throws SignerException {
    Security.addProvider(new BouncyCastleProvider());
    CMSSignedData cmsSignedData = null;
    try {
        if (content == null) {
            if (this.checkHash) {
                cmsSignedData = new CMSSignedData(this.hashes, signedData);
                this.checkHash = false;
            } else {
                cmsSignedData = new CMSSignedData(signedData);
            }

        } else {
            if (this.getAttached(signedData, false) != null) {
                cmsSignedData = new CMSSignedData(signedData);
            } else {
                cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
            }

        }
    } catch (CMSException ex) {
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
    }

    // Quantidade inicial de assinaturas validadas
    int verified = 0;

    Store<?> certStore = cmsSignedData.getCertificates();
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();

    // Realizao da verificao bsica de todas as assinaturas
    while (it.hasNext()) {
        SignatureInformations signatureInfo = new SignatureInformations();
        try {
            SignerInformation signerInfo = (SignerInformation) it.next();
            SignerInformationStore signerInfoStore = signerInfo.getCounterSignatures();

            logger.info("Foi(ram) encontrada(s) " + signerInfoStore.size() + " contra-assinatura(s).");

            @SuppressWarnings("unchecked")
            Collection<?> certCollection = certStore.getMatches(signerInfo.getSID());

            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();

            X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);

            CRLValidator cV = new CRLValidator();
            try {
                cV.validate(varCert);
            } catch (CertificateValidatorCRLException cvce) {
                signatureInfo.getValidatorErrors().add(cvce.getMessage());
                logger.info(cvce.getMessage());
            } catch (CertificateRevocationException cre) {
                signatureInfo.getValidatorErrors().add(cre.getMessage());
                logger.info("certificado revogado");
            }

            PeriodValidator pV = new PeriodValidator();
            try {
                pV.validate(varCert);

            } catch (CertificateValidatorException cve) {
                signatureInfo.getValidatorErrors().add(cve.getMessage());
            }

            if (signerInfo.verify(
                    new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
                verified++;
                logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
            }

            // recupera atributos assinados
            logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
            String varOIDPolicy = PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId();
            AttributeTable signedAttributes = signerInfo.getSignedAttributes();
            if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
                signatureInfo.getValidatorErrors()
                        .add(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
                logger.info(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
                //throw new SignerException(cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
            } else {
                //Validando atributos assinados de acordo com a politica
                Attribute idSigningPolicy = null;
                idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(varOIDPolicy));
                if (idSigningPolicy == null) {
                    signatureInfo.getValidatorErrors().add(
                            cadesMessagesBundle.getString("error.pcks7.attribute.not.found", varOIDPolicy));
                } else {
                    for (Enumeration<?> p = idSigningPolicy.getAttrValues().getObjects(); p
                            .hasMoreElements();) {
                        String policyOnSignature = p.nextElement().toString();
                        for (PolicyFactory.Policies pv : PolicyFactory.Policies.values()) {
                            if (policyOnSignature.contains(pv.getUrl())) {
                                setSignaturePolicy(pv);
                                break;
                            }
                        }
                    }
                }
            }
            Date dataHora = null;
            if (signedAttributes != null) {
                // Valida o atributo ContentType
                Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
                if (attributeContentType == null) {
                    signatureInfo.getValidatorErrors().add(
                            cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                    //throw new SignerException(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                    logger.info(
                            cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
                }

                if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
                    signatureInfo.getValidatorErrors()
                            .add(cadesMessagesBundle.getString("error.content.not.data"));
                    //throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
                    logger.info(cadesMessagesBundle.getString("error.content.not.data"));
                }

                // Validando o atributo MessageDigest
                Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
                if (attributeMessageDigest == null) {
                    throw new SignerException(
                            cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
                }
                // Mostra data e  hora da assinatura, no  carimbo de tempo
                Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime);

                if (timeAttribute != null) {
                    dataHora = (((ASN1UTCTime) timeAttribute.getAttrValues().getObjectAt(0)).getDate());
                    logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
                } else {
                    logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
                }

            }

            if (signaturePolicy == null) {
                signatureInfo.getValidatorErrors().add(
                        cadesMessagesBundle.getString("error.policy.on.component.not.found", varOIDPolicy));
                logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found"));
            } else {
                if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                        .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr()
                        .getObjectIdentifiers() != null) {
                    for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                            .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules()
                            .getSignerRules().getMandatedSignedAttr().getObjectIdentifiers()) {
                        String oi = objectIdentifier.getValue();
                        Attribute signedAtt = signedAttributes.get(new ASN1ObjectIdentifier(oi));
                        logger.info(oi);
                        if (signedAtt == null) {
                            signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString(
                                    "error.signed.attribute.not.found", oi,
                                    signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                        }
                    }
                }
            }

            // recupera os atributos NO assinados
            logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
            AttributeTable unsignedAttributes = signerInfo.getUnsignedAttributes();
            if ((unsignedAttributes == null)
                    || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
                // Apenas info pois a RB no tem atributos no assinados
                logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
            }
            if (signaturePolicy != null) {
                // Validando atributos NO assinados de acordo com a politica
                if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                        .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr()
                        .getObjectIdentifiers() != null) {
                    for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                            .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules()
                            .getSignerRules().getMandatedUnsignedAttr().getObjectIdentifiers()) {
                        String oi = objectIdentifier.getValue();
                        Attribute unSignedAtt = unsignedAttributes.get(new ASN1ObjectIdentifier(oi));
                        logger.info(oi);
                        if (unSignedAtt == null) {
                            signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString(
                                    "error.unsigned.attribute.not.found", oi,
                                    signaturePolicy.getSignPolicyInfo().getSignPolicyIdentifier().getValue()));
                        }
                        if (oi.equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
                            //Verificando timeStamp
                            try {
                                byte[] varSignature = signerInfo.getSignature();
                                Timestamp varTimeStampSigner = validateTimestamp(unSignedAtt, varSignature);
                                signatureInfo.setTimeStampSigner(varTimeStampSigner);
                            } catch (Exception ex) {
                                signatureInfo.getValidatorErrors().add(ex.getMessage());
                                // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo.                  
                            }
                        }
                        if (oi.equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) {
                            logger.info("++++++++++  EscTimeStamp ++++++++++++");
                        }
                    }
                }
            }

            LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance()
                    .getCertificateChain(varCert);
            if (varChain.size() < 3) {
                signatureInfo.getValidatorErrors()
                        .add(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
                logger.info(cadesMessagesBundle.getString("error.no.ca", varCert.getIssuerDN()));
            }
            signatureInfo.setSignDate(dataHora);
            signatureInfo.setChain(varChain);
            signatureInfo.setSignaturePolicy(signaturePolicy);
            this.getSignaturesInfo().add(signatureInfo);

        } catch (OperatorCreationException | java.security.cert.CertificateException ex) {
            signatureInfo.getValidatorErrors().add(ex.getMessage());
            logger.info(ex.getMessage());
        } catch (CMSException ex) {
            // When file is mismatch with sign
            if (ex instanceof CMSSignerDigestMismatchException) {
                signatureInfo.getValidatorErrors()
                        .add(cadesMessagesBundle.getString("error.signature.mismatch"));
                logger.info(cadesMessagesBundle.getString("error.signature.mismatch"));
                throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
            } else {
                signatureInfo.getValidatorErrors()
                        .add(cadesMessagesBundle.getString("error.signature.invalid"));
                logger.info(cadesMessagesBundle.getString("error.signature.invalid"));
                throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex);
            }
        } catch (ParseException e) {
            signatureInfo.getValidatorErrors().add(e.getMessage());
            logger.info(e.getMessage());
        }
    }
    logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
    // TODO Efetuar o parsing da estrutura CMS
    return true;
}

From source file:org.demoiselle.signer.policy.impl.cades.pkcs7.impl.CAdESSigner.java

License:Open Source License

/**
 * Validation is done only on digital signatures with a single signer. Valid
 * only with content of type DATA.: OID ContentType 1.2.840.113549.1.9.3 =
 * OID Data 1.2.840.113549.1.7.1//from w  ww  .  j av  a 2 s  . com
 *
 * @param content Is only necessary to inform if the PKCS7 package is NOT
 *        ATTACHED type. If it is of type attached, this parameter will be
 *        replaced by the contents of the PKCS7 package.
 * @param signedData Value in bytes of the PKCS7 package, such as the
 *        contents of a ".p7s" file. It is not only signature as in the
 *        case of PKCS1.
 * @deprecated moved to CadESChecker
 */
@SuppressWarnings("unchecked")
@Override

public boolean check(byte[] content, byte[] signedData) throws SignerException {
    Security.addProvider(new BouncyCastleProvider());
    CMSSignedData cmsSignedData = null;
    try {
        if (content == null) {
            if (this.checkHash) {
                cmsSignedData = new CMSSignedData(this.hashes, signedData);
                this.checkHash = false;
            } else {
                cmsSignedData = new CMSSignedData(signedData);
            }

        } else {
            cmsSignedData = new CMSSignedData(new CMSProcessableByteArray(content), signedData);
        }
    } catch (CMSException ex) {
        throw new SignerException(cadesMessagesBundle.getString("error.invalid.bytes.pkcs7"), ex);
    }

    // Quantidade inicial de assinaturas validadas
    int verified = 0;

    Store<?> certStore = cmsSignedData.getCertificates();
    SignerInformationStore signers = cmsSignedData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();

    // Realizao da verificao bsica de todas as assinaturas
    while (it.hasNext()) {
        try {
            SignerInformation signer = (SignerInformation) it.next();
            SignerInformationStore s = signer.getCounterSignatures();
            SignatureInformations si = new SignatureInformations();
            logger.info("Foi(ram) encontrada(s) " + s.size() + " contra-assinatura(s).");

            Collection<?> certCollection = certStore.getMatches(signer.getSID());

            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();

            X509Certificate varCert = new JcaX509CertificateConverter().getCertificate(certificateHolder);
            PeriodValidator pV = new PeriodValidator();
            try {
                pV.validate(varCert);

            } catch (CertificateValidatorException cve) {
                si.getValidatorErrors().add(cve.getMessage());
            }

            CRLValidator cV = new CRLValidator();
            try {
                cV.validate(varCert);
            } catch (CertificateValidatorCRLException cvce) {
                si.getValidatorErrors().add(cvce.getMessage());
            }

            if (signer.verify(
                    new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certificateHolder))) {
                verified++;
                logger.info(cadesMessagesBundle.getString("info.signature.valid.seq", verified));
            }

            // Realiza a verificao dos atributos assinados
            logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
            AttributeTable signedAttributes = signer.getSignedAttributes();
            if ((signedAttributes == null) || (signedAttributes != null && signedAttributes.size() == 0)) {
                throw new SignerException(
                        cadesMessagesBundle.getString("error.signed.attribute.table.not.found"));
            }

            // Realiza a verificao dos atributos no assinados
            logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
            AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
            if ((unsignedAttributes == null)
                    || (unsignedAttributes != null && unsignedAttributes.size() == 0)) {
                logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
            }

            // Mostra data e  hora da assinatura, no  carimbo de tempo
            Attribute signingTime = signedAttributes.get(CMSAttributes.signingTime);
            Date dataHora = null;
            if (signingTime != null) {
                dataHora = (((ASN1UTCTime) signingTime.getAttrValues().getObjectAt(0)).getDate());
                logger.info(cadesMessagesBundle.getString("info.date.utc", dataHora));
            } else {
                logger.info(cadesMessagesBundle.getString("info.date.utc", "N/D"));
            }

            logger.info(cadesMessagesBundle.getString("info.attribute.validation"));
            // Valida o atributo ContentType
            Attribute attributeContentType = signedAttributes.get(CMSAttributes.contentType);
            if (attributeContentType == null) {
                throw new SignerException(
                        cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "ContentType"));
            }

            if (!attributeContentType.getAttrValues().getObjectAt(0).equals(ContentInfo.data)) {
                throw new SignerException(cadesMessagesBundle.getString("error.content.not.data"));
            }

            // Validando o atributo MessageDigest
            Attribute attributeMessageDigest = signedAttributes.get(CMSAttributes.messageDigest);
            if (attributeMessageDigest == null) {
                throw new SignerException(
                        cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "MessageDigest"));
            }

            // Validando o atributo MessageDigest
            Attribute idSigningPolicy = null;
            idSigningPolicy = signedAttributes
                    .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
            if (idSigningPolicy == null) {
                throw new SignerException(
                        cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
            }

            //Verificando timeStamp
            try {
                Attribute attributeTimeStamp = null;
                attributeTimeStamp = unsignedAttributes.get(
                        new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
                if (attributeTimeStamp != null) {
                    byte[] varSignature = signer.getSignature();
                    Timestamp varTimeStampSigner = validateTimestamp(attributeTimeStamp, varSignature);
                    si.setTimeStampSigner(varTimeStampSigner);
                }
            } catch (Exception ex) {
                // nas assinaturas feitas na applet o unsignedAttributes.get gera exceo.                  
            }

            LinkedList<X509Certificate> varChain = (LinkedList<X509Certificate>) CAManager.getInstance()
                    .getCertificateChain(varCert);
            si.setSignDate(dataHora);
            si.setChain(varChain);
            si.setSignaturePolicy(signaturePolicy);
            this.getSignatureInfo().add(si);

        } catch (OperatorCreationException | java.security.cert.CertificateException ex) {
            throw new SignerException(ex);
        } catch (CMSException ex) {
            // When file is mismatch with sign
            if (ex instanceof CMSSignerDigestMismatchException)
                throw new SignerException(cadesMessagesBundle.getString("error.signature.mismatch"), ex);
            else
                throw new SignerException(cadesMessagesBundle.getString("error.signature.invalid"), ex);
        } catch (ParseException e) {
            throw new SignerException(e);
        }
    }

    logger.info(cadesMessagesBundle.getString("info.signature.verified", verified));
    // TODO Efetuar o parsing da estrutura CMS
    return true;
}