Search in sources :

Example 6 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project pdfbox by apache.

the class CertInformationCollector method processSignerStore.

/**
 * Processes a signer store and goes through the signers certificate-chain. Adds the found data
 * to the certInfo. Handles only the first signer, although multiple would be possible, but is
 * not yet practicable.
 *
 * @param certificatesStore To get the certificate information from. Certificates will be saved
 * in the certificateStore.
 * @param signedData to get SignerInformation off
 * @param certInfo where to add certificate information
 * @return Signer Information of the processed certificate Store for further usage.
 * @throws IOException on data-processing error
 * @throws CertificateProccessingException on a specific error with a certificate
 */
private SignerInformation processSignerStore(Store<X509CertificateHolder> certificatesStore, CMSSignedData signedData, CertSignatureInformation certInfo) throws IOException, CertificateProccessingException {
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    SignerInformation signerInformation = signers.iterator().next();
    Collection<X509CertificateHolder> matches = certificatesStore.getMatches(signerInformation.getSID());
    X509Certificate certificate = getCertFromHolder(matches.iterator().next());
    Collection<X509CertificateHolder> allCerts = certificatesStore.getMatches(null);
    addAllCerts(allCerts);
    traverseChain(certificate, certInfo, MAX_CERTIFICATE_CHAIN_DEPTH);
    return signerInformation;
}
Also used : X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) SignerInformation(org.bouncycastle.cms.SignerInformation) X509Certificate(java.security.cert.X509Certificate)

Example 7 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project signer by demoiselle.

the class CAdESChecker method check.

/**
 * 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
 *
 * @params 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.
 * @params 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 validação 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 {
            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();
    // Realização da verificação básica 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);
            PeriodValidator pV = new PeriodValidator();
            try {
                pV.validate(varCert);
            } catch (CertificateValidatorException cve) {
                signatureInfo.getValidatorErrors().add(cve.getMessage());
            }
            CRLValidator cV = new CRLValidator();
            try {
                cV.validate(varCert);
            } catch (CertificateValidatorCRLException cvce) {
                signatureInfo.getValidatorErrors().add(cvce.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"));
            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"));
            } else {
                // Validando atributos assinados de acordo com a politica
                Attribute idSigningPolicy = null;
                idSigningPolicy = signedAttributes.get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId.getId()));
                if (idSigningPolicy == null) {
                    signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.pcks7.attribute.not.found", "idSigningPolicy"));
                } 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;
                            }
                        }
                    }
                }
            }
            if (signaturePolicy == null) {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.policy.on.component.not.found", "idSigningPolicy"));
                logger.info(cadesMessagesBundle.getString("error.policy.on.component.not.found", "idSigningPolicy"));
            } 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()));
                        }
                    }
                }
            }
            // Mostra data e  hora da assinatura, não é carimbo de tempo
            Attribute timeAttribute = signedAttributes.get(CMSAttributes.signingTime);
            Date dataHora = null;
            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"));
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("info.date.utc", "N/D"));
            }
            // recupera os atributos NÃO 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 não tem atributos não assinados
                logger.info(cadesMessagesBundle.getString("error.unsigned.attribute.table.not.found"));
            }
            if (signaturePolicy != null) {
                // Validando atributos NÃO 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 exceção.
                            }
                        }
                        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"));
            } else {
                signatureInfo.getValidatorErrors().add(cadesMessagesBundle.getString("error.signature.invalid"));
                logger.info(cadesMessagesBundle.getString("error.signature.invalid"));
            }
        } catch (ParseException e) {
            signatureInfo.getValidatorErrors().add(e.getMessage());
            logger.info(e.getMessage());
        } catch (Exception 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;
}
Also used : PolicyFactory(org.demoiselle.signer.policy.engine.factory.PolicyFactory) Attribute(org.bouncycastle.asn1.cms.Attribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) SignerInformation(org.bouncycastle.cms.SignerInformation) CRLValidator(org.demoiselle.signer.core.validator.CRLValidator) Timestamp(org.demoiselle.signer.timestamp.Timestamp) SignatureInformations(org.demoiselle.signer.policy.impl.cades.SignatureInformations) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PeriodValidator(org.demoiselle.signer.core.validator.PeriodValidator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) ObjectIdentifier(org.demoiselle.signer.policy.engine.asn1.etsi.ObjectIdentifier) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) ParseException(java.text.ParseException) TSPException(org.bouncycastle.tsp.TSPException) CMSException(org.bouncycastle.cms.CMSException) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) IOException(java.io.IOException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) LinkedList(java.util.LinkedList) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ParseException(java.text.ParseException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 8 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project signer by demoiselle.

the class CAdESSigner method updateWithCounterSignature.

@SuppressWarnings("static-access")
private CMSSignedData updateWithCounterSignature(final CMSSignedData counterSignature, final CMSSignedData originalSignature, SignerId selector) {
    // Retrieve the SignerInformation from the countersigned signature
    final SignerInformationStore originalSignerInfos = originalSignature.getSignerInfos();
    // Retrieve the SignerInformation from the countersignature
    final SignerInformationStore signerInfos = counterSignature.getSignerInfos();
    // Add the countersignature
    SignerInformation updatedSI = originalSignature.getSignerInfos().get(selector).addCounterSigners(originalSignerInfos.get(selector), signerInfos);
    // Create updated SignerInformationStore
    Collection<SignerInformation> counterSignatureInformationCollection = new ArrayList<SignerInformation>();
    counterSignatureInformationCollection.add(updatedSI);
    SignerInformationStore signerInformationStore = new SignerInformationStore(counterSignatureInformationCollection);
    // Return new, updated signature
    return CMSSignedData.replaceSigners(originalSignature, signerInformationStore);
}
Also used : SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) ArrayList(java.util.ArrayList) SignerInformation(org.bouncycastle.cms.SignerInformation)

Example 9 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project signer by demoiselle.

the class CAdESSigner method check.

/**
 * 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
 *
 * @params 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.
 * @params 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.
 */
@SuppressWarnings("unchecked")
// TODO: Implementar validação de co-assinaturas
@Override
@Deprecated
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();
    // Realização da verificação básica 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 verificação 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 verificação dos atributos não 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, não é 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 exceção.
            }
            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;
}
Also used : Attribute(org.bouncycastle.asn1.cms.Attribute) SignedOrUnsignedAttribute(org.demoiselle.signer.policy.impl.cades.pkcs7.attribute.SignedOrUnsignedAttribute) AttributeTable(org.bouncycastle.asn1.cms.AttributeTable) ASN1UTCTime(org.bouncycastle.asn1.ASN1UTCTime) SignerInformation(org.bouncycastle.cms.SignerInformation) CertificateException(java.security.cert.CertificateException) CRLValidator(org.demoiselle.signer.core.validator.CRLValidator) Timestamp(org.demoiselle.signer.timestamp.Timestamp) SignatureInformations(org.demoiselle.signer.policy.impl.cades.SignatureInformations) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) JcaX509CertificateConverter(org.bouncycastle.cert.jcajce.JcaX509CertificateConverter) PeriodValidator(org.demoiselle.signer.core.validator.PeriodValidator) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) CMSProcessableByteArray(org.bouncycastle.cms.CMSProcessableByteArray) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateTrustPoint(org.demoiselle.signer.policy.engine.asn1.etsi.CertificateTrustPoint) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) ParseException(java.text.ParseException) TSPException(org.bouncycastle.tsp.TSPException) CertificateEncodingException(java.security.cert.CertificateEncodingException) CMSException(org.bouncycastle.cms.CMSException) CertificateValidatorCRLException(org.demoiselle.signer.core.exception.CertificateValidatorCRLException) CMSSignerDigestMismatchException(org.bouncycastle.cms.CMSSignerDigestMismatchException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) LinkedList(java.util.LinkedList) CertificateValidatorException(org.demoiselle.signer.core.exception.CertificateValidatorException) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) ParseException(java.text.ParseException) SignerException(org.demoiselle.signer.policy.impl.cades.SignerException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Example 10 with SignerInformation

use of org.bouncycastle.cms.SignerInformation in project signer by demoiselle.

the class TimeStampOperator method validate.

/**
 * Validate a time stamp
 *
 * @param content if it is assigned, the parameter hash must to be null
 * @param timeStamp timestamp to be validated
 * @param hash if it is assigned, the parameter content must to be null
 * @throws CertificateCoreException validate exception
 */
@SuppressWarnings("unchecked")
public void validate(byte[] content, byte[] timeStamp, byte[] hash) throws CertificateCoreException {
    try {
        TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(timeStamp));
        CMSSignedData s = timeStampToken.toCMSSignedData();
        int verified = 0;
        Store<?> certStore = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            SignerInformation signer = it.next();
            Collection<?> certCollection = certStore.getMatches(signer.getSID());
            Iterator<?> certIt = certCollection.iterator();
            X509CertificateHolder cert = (X509CertificateHolder) certIt.next();
            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert))) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
        }
        logger.info(timeStampMessagesBundle.getString("info.signature.verified", verified));
        // Valida o hash  incluso no carimbo de tempo com hash do arquivo carimbado
        byte[] calculatedHash = null;
        if (content != null) {
            Digest digest = DigestFactory.getInstance().factoryDefault();
            digest.setAlgorithm(DigestAlgorithmEnum.SHA_256);
            calculatedHash = digest.digest(content);
        } else {
            calculatedHash = hash;
        }
        if (Arrays.equals(calculatedHash, timeStampToken.getTimeStampInfo().getMessageImprintDigest())) {
            logger.info(timeStampMessagesBundle.getString("info.timestamp.hash.ok"));
        } else {
            throw new CertificateCoreException(timeStampMessagesBundle.getString("info.timestamp.hash.nok"));
        }
    } catch (TSPException | IOException | CMSException | OperatorCreationException | CertificateException ex) {
        throw new CertificateCoreException(ex.getMessage());
    }
}
Also used : Digest(org.demoiselle.signer.cryptography.Digest) SignerInformation(org.bouncycastle.cms.SignerInformation) JcaSimpleSignerInfoVerifierBuilder(org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder) CertificateException(java.security.cert.CertificateException) IOException(java.io.IOException) CMSSignedData(org.bouncycastle.cms.CMSSignedData) CertificateCoreException(org.demoiselle.signer.core.exception.CertificateCoreException) SignerInformationStore(org.bouncycastle.cms.SignerInformationStore) X509CertificateHolder(org.bouncycastle.cert.X509CertificateHolder) TSPException(org.bouncycastle.tsp.TSPException) TimeStampToken(org.bouncycastle.tsp.TimeStampToken) OperatorCreationException(org.bouncycastle.operator.OperatorCreationException) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) CMSException(org.bouncycastle.cms.CMSException)

Aggregations

SignerInformation (org.bouncycastle.cms.SignerInformation)32 SignerInformationStore (org.bouncycastle.cms.SignerInformationStore)21 CMSSignedData (org.bouncycastle.cms.CMSSignedData)19 X509Certificate (java.security.cert.X509Certificate)17 X509CertificateHolder (org.bouncycastle.cert.X509CertificateHolder)13 JcaSimpleSignerInfoVerifierBuilder (org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder)13 CMSException (org.bouncycastle.cms.CMSException)10 JcaX509CertificateConverter (org.bouncycastle.cert.jcajce.JcaX509CertificateConverter)8 CertificateException (java.security.cert.CertificateException)7 Attribute (org.bouncycastle.asn1.cms.Attribute)7 AttributeTable (org.bouncycastle.asn1.cms.AttributeTable)7 CMSProcessableByteArray (org.bouncycastle.cms.CMSProcessableByteArray)7 OperatorCreationException (org.bouncycastle.operator.OperatorCreationException)7 IOException (java.io.IOException)6 ArrayList (java.util.ArrayList)6 Collection (java.util.Collection)6 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)6 FileInputStream (java.io.FileInputStream)4 CertStore (java.security.cert.CertStore)4 Date (java.util.Date)4