Example usage for org.bouncycastle.cms SignerInformation getUnsignedAttributes

List of usage examples for org.bouncycastle.cms SignerInformation getUnsignedAttributes

Introduction

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

Prototype

public AttributeTable getUnsignedAttributes() 

Source Link

Document

return a table of the unsigned attributes indexed by the OID of the attribute.

Usage

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

License:Open Source License

@Override
@SuppressWarnings("unchecked")
public List<X509Certificate> getCertificates() {
    List<X509Certificate> list = new ArrayList<X509Certificate>();

    try {//from   w  w  w  .ja v a2  s .  co  m

        if (!onlyExtended) {
            LOG.fine(cmsSignedData.getCertificates().getMatches(null).size() + " certificate in collection");
            for (X509CertificateHolder ch : (Collection<X509CertificateHolder>) cmsSignedData.getCertificates()
                    .getMatches(null)) {
                X509Certificate c = new X509CertificateObject(ch.toASN1Structure());
                LOG.fine("Certificate for subject " + c.getSubjectX500Principal());
                if (!list.contains(c)) {
                    list.add(c);
                }
            }
        }

        // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
        SignerInformation si = cmsSignedData.getSignerInfos().get(signerId);
        if (si != null && si.getUnsignedAttributes() != null
                && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_certValues) != null) {

            DERSequence seq = (DERSequence) si.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_certValues).getAttrValues().getObjectAt(0);

            for (int i = 0; i < seq.size(); i++) {
                X509CertificateStructure cs = X509CertificateStructure.getInstance(seq.getObjectAt(i));
                X509Certificate c = new X509CertificateObject(cs);
                if (!list.contains(c)) {
                    list.add(c);
                }
            }
        }
    } catch (CertificateParsingException e) {
        throw new RuntimeException(e);
    } catch (StoreException e) {
        throw new RuntimeException(e);
    }

    return list;
}

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

License:Open Source License

@SuppressWarnings("unchecked")
@Override//from   w  w  w .  j av a 2  s  . co m
public List<X509CRL> getCRLsFromSignature() {
    List<X509CRL> list = new ArrayList<X509CRL>();

    try {
        // Add certificates contained in SignedData
        for (CertificateList cl : (Collection<CertificateList>) cmsSignedData.getCRLs().getMatches(null)) {
            X509CRLObject crl = new X509CRLObject(cl);
            list.add(crl);
        }

        // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
        SignerInformation si = cmsSignedData.getSignerInfos().get(signerId);
        if (si != null && si.getUnsignedAttributes() != null
                && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationValues) != null) {

            RevocationValues revValues = RevocationValues.getInstance(si.getUnsignedAttributes()
                    .get(PKCSObjectIdentifiers.id_aa_ets_revocationValues).getAttrValues().getObjectAt(0));

            for (CertificateList crlObj : revValues.getCrlVals()) {
                X509CRLObject crl = new X509CRLObject(crlObj);
                list.add(crl);
            }
        }
    } catch (StoreException e) {
        throw new RuntimeException(e);
    } catch (CRLException e) {
        throw new RuntimeException(e);
    }

    return list;
}

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

License:Open Source License

@Override
public List<BasicOCSPResp> getOCSPResponsesFromSignature() {
    List<BasicOCSPResp> list = new ArrayList<BasicOCSPResp>();

    // Add certificates in CAdES-XL certificate-values inside SignerInfo attribute if present
    SignerInformation si = cmsSignedData.getSignerInfos().get(signerId);
    if (si != null && si.getUnsignedAttributes() != null
            && si.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_ets_revocationValues) != null) {

        RevocationValues revValues = RevocationValues.getInstance(si.getUnsignedAttributes()
                .get(PKCSObjectIdentifiers.id_aa_ets_revocationValues).getAttrValues().getObjectAt(0));

        for (BasicOCSPResponse ocspObj : revValues.getOcspVals()) {
            BasicOCSPResp bOcspObj = new BasicOCSPResp(ocspObj);
            ;//  ww w . j  av a  2 s .  co  m
            list.add(bOcspObj);
        }
    }

    return list;
}

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

License:Open Source License

/**
 * @param signerInformation/*from  w w w.  j ava 2 s .  c o  m*/
 * @return the existing unsigned attributes or an empty attributes hashtable
 */
public static AttributeTable getUnsignedAttributes(final SignerInformation signerInformation) {
    final AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Attribute>());
    } else {
        return unsignedAttributes;
    }
}

From source file:net.jsign.pe.PEFile.java

License:Apache License

/**
 * Print detailed informations about the PE file.
 *//*from ww w.  ja  v  a 2  s  .  com*/
public void printInfo(PrintWriter out) {
    out.println("PE File");
    out.println("  Name:          " + raf.getName());
    out.println("  Size:          " + raf.length());
    out.println("  Last Modified: " + new Date(raf.lastModified()));
    out.println();

    out.println("PE Header");
    out.println("  Machine:                    " + getMachineType());
    out.println("  Number of sections:         " + getNumberOfSections());
    out.println("  Timestamp:                  " + getTimeDateStamp());
    out.println("  Pointer to symbol table:    0x" + Long.toHexString(getPointerToSymbolTable()));
    out.println("  Number of symbols:          " + getNumberOfSymbols());
    out.println("  Size of optional header:    " + getSizeOfOptionalHeader());
    out.println("  Characteristics:            0x" + Long.toBinaryString(getCharacteristics()));
    out.println();

    out.println("Optional Header");
    PEFormat format = getFormat();
    out.println(
            "  PE Format:                  0x" + Integer.toHexString(format.value) + " (" + format.label + ")");
    out.println("  Linker version:             " + getMajorLinkerVersion() + "." + getMinorLinkerVersion());
    out.println("  Size of code:               " + getSizeOfCode());
    out.println("  Size of initialized data:   " + getSizeOfInitializedData());
    out.println("  Size of uninitialized data: " + getSizeOfUninitializedData());
    out.println("  Address of entry point:     0x" + Long.toHexString(getAddressOfEntryPoint()));
    out.println("  Base of code:               0x" + Long.toHexString(getBaseOfCode()));
    if (PEFormat.PE32.equals(getFormat())) {
        out.println("  Base of data:               0x" + Long.toHexString(getBaseOfData()));
    }
    out.println("  Image base:                 0x" + Long.toHexString(getImageBase()));
    out.println("  Section alignment:          " + getSectionAlignment());
    out.println("  File alignment:             " + getFileAlignment());
    out.println("  Operating system version:   " + getMajorOperatingSystemVersion() + "."
            + getMinorOperatingSystemVersion());
    out.println("  Image version:              " + getMajorImageVersion() + "." + getMinorImageVersion());
    out.println(
            "  Subsystem version:          " + getMajorSubsystemVersion() + "." + getMinorSubsystemVersion());
    out.println("  Size of image:              " + getSizeOfImage());
    out.println("  Size of headers:            " + getSizeOfHeaders());
    out.println("  Checksum:                   0x" + Long.toHexString(getCheckSum()));
    out.println("  Checksum (computed):        0x" + Long.toHexString(computeChecksum()));
    out.println("  Subsystem:                  " + getSubsystem());
    out.println("  DLL characteristics:        0x" + Long.toBinaryString(getDllCharacteristics()));
    out.println("  Size of stack reserve:      " + getSizeOfStackReserve());
    out.println("  Size of stack commit:       " + getSizeOfStackCommit());
    out.println("  Size of heap reserve:       " + getSizeOfHeapReserve());
    out.println("  Size of heap commit:        " + getSizeOfHeapCommit());
    out.println("  Number of RVA and sizes:    " + getNumberOfRvaAndSizes());
    out.println();

    out.println("Data Directory");
    for (DataDirectoryType type : DataDirectoryType.values()) {
        DataDirectory entry = getDataDirectory(type);
        if (entry != null && entry.getVirtualAddress() != 0) {
            out.printf("  %-30s 0x%08x %8d bytes\n", type, entry.getVirtualAddress(), entry.getSize());
        }
    }
    out.println();

    int sectionTableOffset = getDataDirectoryOffset() + 8 * getNumberOfRvaAndSizes();
    out.println("Sections");
    out.println("      Name     Virtual Size  Virtual Address  Raw Data Size  Raw Data Ptr  Characteristics");
    for (int i = 0; i < getNumberOfSections(); i++) {
        Section section = new Section(this, sectionTableOffset + 40 * i);
        out.printf("  #%d  %-8s     %8d       0x%08x       %8d    0x%08x  %s\n", i + 1, section.getName(),
                section.getVirtualSize(), section.getVirtualAddress(), section.getSizeOfRawData(),
                section.getPointerToRawData(), section.getCharacteristics());
    }
    out.println();

    List<CMSSignedData> signatures = getSignatures();
    if (!signatures.isEmpty()) {
        out.println("Signatures");
        for (CMSSignedData signedData : signatures) {
            SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next();
            X509CertificateHolder certificate = (X509CertificateHolder) signedData.getCertificates()
                    .getMatches(signerInformation.getSID()).iterator().next();

            String commonName = certificate.getSubject().getRDNs(X509ObjectIdentifiers.commonName)[0].getFirst()
                    .getValue().toString();

            AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
            boolean timestamped = unsignedAttributes != null
                    && (unsignedAttributes.get(PKCSObjectIdentifiers.pkcs_9_at_counterSignature) != null
                            || unsignedAttributes.get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID) != null);
            DigestAlgorithm algorithm = DigestAlgorithm
                    .of(signerInformation.getDigestAlgorithmID().getAlgorithm());
            out.println("  " + commonName + "  " + (algorithm != null ? "[" + algorithm.id + "]  " : "")
                    + (timestamped ? "(timestamped)" : ""));
        }
    }
}

From source file:net.jsign.SignatureAssert.java

License:Apache License

public static void assertTimestamped(String message, CMSSignedData signedData) {
    SignerInformation signerInformation = signedData.getSignerInfos().getSigners().iterator().next();

    AttributeTable unsignedAttributes = signerInformation.getUnsignedAttributes();
    Assert.assertNotNull(message + " (missing unauthenticated attributse)", unsignedAttributes);

    Attribute authenticodeTimestampAttribute = unsignedAttributes.get(CMSAttributes.counterSignature);
    Attribute rfc3161TimestampAttribute = unsignedAttributes
            .get(AuthenticodeObjectIdentifiers.SPC_RFC3161_OBJID);

    Assert.assertTrue(message + " (no counter signature attribute found)",
            authenticodeTimestampAttribute != null || rfc3161TimestampAttribute != null);

    if (authenticodeTimestampAttribute != null) {
        Assert.assertNotNull(message + " (counter signature attribute value is null)",
                authenticodeTimestampAttribute.getAttributeValues());
        Assert.assertTrue(message + " (counter signature attribute value is empty)",
                authenticodeTimestampAttribute.getAttributeValues().length > 0);
    } else {//  w ww. j a  v  a 2  s.  co  m
        Assert.assertNotNull(message + " (counter signature attribute value is null)",
                rfc3161TimestampAttribute.getAttributeValues());
        Assert.assertTrue(message + " (counter signature attribute value is empty)",
                rfc3161TimestampAttribute.getAttributeValues().length > 0);
    }

}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.7
 *//*  w w  w  .  j a v a  2s  . com*/
@Test
public void shouldCmsObjectHaveNoUnsignedAttribute() throws Exception {
    Collection<?> signers = signedDataParser.getSignerInfos().getSigners();
    SignerInformation signer = (SignerInformation) signers.iterator().next();

    assertNull(signer.getUnsignedAttributes());
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.6.7
 *//*  w  ww. j  av  a 2  s .c o  m*/
private void verifyUnsignedAttributes(SignerInformation signer) {
    validationResult.rejectIfFalse(signer.getUnsignedAttributes() == null, UNSIGNED_ATTRS_OMITTED);
}

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/*ww  w.  j a  va 2s  .c  om*/
 *
 * @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//  ww  w  .j a va  2s  .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;
}