Example usage for org.bouncycastle.cms CMSSignedData getSignerInfos

List of usage examples for org.bouncycastle.cms CMSSignedData getSignerInfos

Introduction

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

Prototype

public SignerInformationStore getSignerInfos() 

Source Link

Document

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

Usage

From source file: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/* w ww.  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.
 * @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;
}

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

License:Open Source License

private Collection<X509Certificate> getSignersCertificates(CMSSignedData previewSignerData) {
    Collection<X509Certificate> result = new HashSet<X509Certificate>();
    Store<?> certStore = previewSignerData.getCertificates();
    SignerInformationStore signers = previewSignerData.getSignerInfos();
    Iterator<?> it = signers.getSigners().iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        @SuppressWarnings("unchecked")
        Collection<?> certCollection = certStore.getMatches(signer.getSID());
        Iterator<?> certIt = certCollection.iterator();
        X509CertificateHolder certificateHolder = (X509CertificateHolder) certIt.next();
        try {//from w w  w.  j  a  va  2s  . c  o  m
            result.add(new JcaX509CertificateConverter().getCertificate(certificateHolder));
        } catch (CertificateException error) {
        }
    }
    return result;

}

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

License:Open Source License

private byte[] doSign(byte[] content, byte[] previewSignature) {
    try {/*from ww  w  . j ava 2  s  . c o  m*/
        Security.addProvider(new BouncyCastleProvider());

        // Completa os certificados ausentes da cadeia, se houver
        if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) {
            this.certificate = (X509Certificate) this.certificateChain[0];
        }

        this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate);

        if (this.certificateChain.length < 3) {
            throw new SignerException(
                    cadesMessagesBundle.getString("error.no.ca", this.certificate.getIssuerDN()));
        }

        Certificate[] certStore = new Certificate[] {};

        CMSSignedData cmsPreviewSignedData = null;
        // Caso seja co-assinatura ou contra-assinatura
        // Importar todos os certificados da assinatura anterior
        if (previewSignature != null && previewSignature.length > 0) {
            cmsPreviewSignedData = new CMSSignedData(new CMSAbsentContent(), previewSignature);
            Collection<X509Certificate> previewCerts = this.getSignersCertificates(cmsPreviewSignedData);
            //previewCerts.add(this.certificate);
            certStore = previewCerts.toArray(new Certificate[] {});
        }

        setCertificateManager(new CertificateManager(this.certificate));

        // Recupera a lista de algoritmos da politica e o tamanho minimo da
        // chave
        List<AlgAndLength> listOfAlgAndLength = new ArrayList<AlgAndLength>();

        for (AlgAndLength algLength : signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy()
                .getCommonRules().getAlgorithmConstraintSet().getSignerAlgorithmConstraints()
                .getAlgAndLengths()) {
            listOfAlgAndLength.add(algLength);
        }
        AlgAndLength algAndLength = null;

        // caso o algoritmo tenha sido informado como parmetro ir
        // verificar se o mesmo  permitido pela politica
        if (this.pkcs1.getAlgorithm() != null) {
            String varSetedAlgorithmOID = AlgorithmNames.getOIDByAlgorithmName(this.pkcs1.getAlgorithm());
            for (AlgAndLength algLength : listOfAlgAndLength) {
                if (algLength.getAlgID().getValue().equalsIgnoreCase(varSetedAlgorithmOID)) {
                    algAndLength = algLength;
                    SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum
                            .valueOf(this.pkcs1.getAlgorithm());
                    String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
                    ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg()
                            .getAlgorithm();
                    varObjectIdentifier.setValue(varOIDAlgorithmHash);
                    AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
                    varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
                    signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);
                }
            }
        } else {
            algAndLength = listOfAlgAndLength.get(1);
            this.pkcs1.setAlgorithm(AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue()));
            SignerAlgorithmEnum varSignerAlgorithmEnum = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm());
            String varOIDAlgorithmHash = varSignerAlgorithmEnum.getOIDAlgorithmHash();
            ObjectIdentifier varObjectIdentifier = signaturePolicy.getSignPolicyHashAlg().getAlgorithm();
            varObjectIdentifier.setValue(varOIDAlgorithmHash);
            AlgorithmIdentifier varAlgorithmIdentifier = signaturePolicy.getSignPolicyHashAlg();
            varAlgorithmIdentifier.setAlgorithm(varObjectIdentifier);
            signaturePolicy.setSignPolicyHashAlg(varAlgorithmIdentifier);

        }
        if (algAndLength == null) {
            throw new SignerException(cadesMessagesBundle.getString("error.no.algorithm.policy"));
        }
        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algAndLength.getAlgID().getValue()));
        logger.info(cadesMessagesBundle.getString("info.algorithm.name",
                AlgorithmNames.getAlgorithmNameByOID(algAndLength.getAlgID().getValue())));
        logger.info(cadesMessagesBundle.getString("info.min.key.length", algAndLength.getMinKeyLength()));
        // Recupera o tamanho minimo da chave para validacao
        logger.info(cadesMessagesBundle.getString("info.validating.key.length"));
        int keyLegth = ((RSAKey) certificate.getPublicKey()).getModulus().bitLength();
        if (keyLegth < algAndLength.getMinKeyLength()) {
            throw new SignerException(cadesMessagesBundle.getString("error.min.key.length",
                    algAndLength.getMinKeyLength().toString(), keyLegth));
        }

        AttributeFactory attributeFactory = AttributeFactory.getInstance();

        // Consulta e adiciona os atributos assinados
        ASN1EncodableVector signedAttributes = new ASN1EncodableVector();

        logger.info(cadesMessagesBundle.getString("info.signed.attribute"));
        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                .getSignerAndVeriferRules().getSignerRules().getMandatedSignedAttr()
                .getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                    .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules()
                    .getMandatedSignedAttr().getObjectIdentifiers()) {

                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                        .factory(objectIdentifier.getValue());
                signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain, content,
                        signaturePolicy, this.hash);
                signedAttributes.add(signedOrUnsignedAttribute.getValue());
            }
        }

        // Monta a tabela de atributos assinados
        AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);

        // Create the table table generator that will added to the Signer
        // builder
        CMSAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        // Recupera o(s) certificado(s) de confianca para validacao
        Collection<X509Certificate> trustedCAs = new HashSet<X509Certificate>();

        Collection<CertificateTrustPoint> ctp = signaturePolicy.getSignPolicyInfo()
                .getSignatureValidationPolicy().getCommonRules().getSigningCertTrustCondition()
                .getSignerTrustTrees().getCertificateTrustPoints();
        for (CertificateTrustPoint certificateTrustPoint : ctp) {
            logger.info(cadesMessagesBundle.getString("info.trust.point",
                    certificateTrustPoint.getTrustpoint().getSubjectDN().toString()));
            trustedCAs.add(certificateTrustPoint.getTrustpoint());
        }

        // Efetua a validacao das cadeias do certificado baseado na politica
        Collection<X509Certificate> certificateChainTrusted = new HashSet<X509Certificate>();
        for (Certificate certCA : certificateChain) {
            certificateChainTrusted.add((X509Certificate) certCA);
        }
        X509Certificate rootOfCertificate = null;
        for (X509Certificate tcac : certificateChainTrusted) {
            logger.info(tcac.getIssuerDN().toString());
            if (CAManager.getInstance().isRootCA(tcac)) {
                rootOfCertificate = tcac;
            }
        }
        if (trustedCAs.contains(rootOfCertificate)) {
            logger.info(cadesMessagesBundle.getString("info.trust.in.point", rootOfCertificate.getSubjectDN()));
        } else {
            // No encontrou na poltica, verificar nas cadeias do
            // componente chain-icp-brasil provavelmente certificado de
            // homologao.
            logger.warn(cadesMessagesBundle.getString("info.trust.poin.homolog"));
            CAManager.getInstance().validateRootCAs(certificateChainTrusted, certificate);
        }

        //  validade da politica
        logger.info(cadesMessagesBundle.getString("info.policy.valid.period"));
        PolicyValidator pv = new PolicyValidator(this.signaturePolicy, this.policyName);
        pv.validate();
        // Realiza a assinatura do conteudo
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addCertificates(this.generatedCertStore(certStore));
        String algorithmOID = algAndLength.getAlgID().getValue();

        logger.info(cadesMessagesBundle.getString("info.algorithm.id", algorithmOID));
        SignerInfoGenerator signerInfoGenerator = new JcaSimpleSignerInfoGeneratorBuilder()
                .setSignedAttributeGenerator(signedAttributeGenerator).setUnsignedAttributeGenerator(null)
                .build(AlgorithmNames.getAlgorithmNameByOID(algorithmOID), this.pkcs1.getPrivateKey(),
                        this.certificate);
        gen.addSignerInfoGenerator(signerInfoGenerator);

        CMSTypedData cmsTypedData;
        // para assinatura do hash, content nulo
        if (content == null) {
            cmsTypedData = new CMSAbsentContent();
        } else {
            cmsTypedData = new CMSProcessableByteArray(content);
        }

        // Efetua a assinatura digital do contedo
        CMSSignedData cmsSignedData = gen.generate(cmsTypedData, this.attached);
        setAttached(false);

        // Consulta e adiciona os atributos no assinados//

        ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();

        logger.info(cadesMessagesBundle.getString("info.unsigned.attribute"));
        Collection<SignerInformation> vNewSigners = cmsSignedData.getSignerInfos().getSigners();

        Iterator<SignerInformation> it = vNewSigners.iterator();
        SignerInformation oSi = it.next();

        if (signaturePolicy.getSignPolicyInfo().getSignatureValidationPolicy().getCommonRules()
                .getSignerAndVeriferRules().getSignerRules().getMandatedUnsignedAttr()
                .getObjectIdentifiers() != null) {
            for (ObjectIdentifier objectIdentifier : signaturePolicy.getSignPolicyInfo()
                    .getSignatureValidationPolicy().getCommonRules().getSignerAndVeriferRules().getSignerRules()
                    .getMandatedUnsignedAttr().getObjectIdentifiers()) {
                SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                        .factory(objectIdentifier.getValue());
                if (signedOrUnsignedAttribute.getOID()
                        .equalsIgnoreCase(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId())) {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
                            this.certificateChainTimeStamp, oSi.getSignature(), signaturePolicy, this.hash);
                }
                if (signedOrUnsignedAttribute.getOID().equalsIgnoreCase("1.2.840.113549.1.9.16.2.25")) //EscTimeStamp
                {

                    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                    outputStream.write(oSi.getSignature());
                    AttributeTable varUnsignedAttributes = oSi.getUnsignedAttributes();
                    Attribute varAttribute = varUnsignedAttributes.get(new ASN1ObjectIdentifier(
                            PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(
                            new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_certificateRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    varAttribute = varUnsignedAttributes.get(
                            new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_ets_revocationRefs.getId()));
                    outputStream.write(varAttribute.getAttrType().getEncoded());
                    outputStream.write(varAttribute.getAttrValues().getEncoded());
                    escTimeStampContent = outputStream.toByteArray();
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(),
                            this.certificateChainTimeStamp, escTimeStampContent, signaturePolicy, this.hash);
                }

                else {
                    signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), certificateChain,
                            oSi.getSignature(), signaturePolicy, this.hash);
                }
                unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
                AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
                vNewSigners.remove(oSi);
                oSi = SignerInformation.replaceUnsignedAttributes(oSi, unsignedAttributesTable);
                vNewSigners.add(oSi);
            }
        }

        //TODO Estudar este mtodo de contra-assinatura posteriormente
        if (previewSignature != null && previewSignature.length > 0) {
            vNewSigners.addAll(cmsPreviewSignedData.getSignerInfos().getSigners());
        }
        SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
        CMSSignedData oSignedData = cmsSignedData;
        cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);

        byte[] result = cmsSignedData.getEncoded();

        logger.info(cadesMessagesBundle.getString("info.signature.ok"));

        return result;

    } catch (CMSException | IOException | OperatorCreationException | CertificateEncodingException ex) {
        throw new SignerException(ex);
    }
}

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

License:Open Source License

@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);
}

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

License:Open Source License

@Override
public byte[] doCounterSign(byte[] previewCMSSignature) {
    try {/* ww w  .  java 2  s. c  o m*/
        Security.addProvider(new BouncyCastleProvider());

        // Reading a P7S file that is preview signature.
        CMSSignedData cmsPreviewSignedData = new CMSSignedData(previewCMSSignature);

        // Build BouncyCastle object that is a set of signatures
        Collection<SignerInformation> previewSigners = cmsPreviewSignedData.getSignerInfos().getSigners();

        for (SignerInformation previewSigner : previewSigners) {
            // build a counter-signature per previewSignature
            byte[] previewSignatureFromSigner = previewSigner.getSignature();
            CMSSignedData cmsCounterSignedData = new CMSSignedData(this.doSign(previewSignatureFromSigner));
            cmsPreviewSignedData = this.updateWithCounterSignature(cmsCounterSignedData, cmsPreviewSignedData,
                    previewSigner.getSID());
        }
        return cmsPreviewSignedData.getEncoded();
    } catch (Throwable error) {
        throw new SignerException(error);
    }
}

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

License:Open Source License

@Override
public byte[] doTimeStampForSignature(byte[] signature) throws SignerException {
    try {/* www  . j ava 2  s . c  o  m*/
        Security.addProvider(new BouncyCastleProvider());
        CMSSignedData cmsSignedData = new CMSSignedData(signature);
        SignerInformationStore signers = cmsSignedData.getSignerInfos();
        Iterator<?> it = signers.getSigners().iterator();
        SignerInformation signer = (SignerInformation) it.next();
        AttributeFactory attributeFactory = AttributeFactory.getInstance();
        ASN1EncodableVector unsignedAttributes = new ASN1EncodableVector();
        SignedOrUnsignedAttribute signedOrUnsignedAttribute = attributeFactory
                .factory(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId());
        signedOrUnsignedAttribute.initialize(this.pkcs1.getPrivateKey(), this.getCertificateChain(),
                signer.getSignature(), signaturePolicy, null);
        unsignedAttributes.add(signedOrUnsignedAttribute.getValue());
        AttributeTable unsignedAttributesTable = new AttributeTable(unsignedAttributes);
        List<SignerInformation> vNewSigners = new ArrayList<SignerInformation>();
        vNewSigners.add(SignerInformation.replaceUnsignedAttributes(signer, unsignedAttributesTable));
        SignerInformationStore oNewSignerInformationStore = new SignerInformationStore(vNewSigners);
        CMSSignedData oSignedData = cmsSignedData;
        cmsSignedData = CMSSignedData.replaceSigners(oSignedData, oNewSignerInformationStore);
        byte[] result = cmsSignedData.getEncoded();
        return result;
    } catch (CMSException ex) {
        throw new SignerException(ex.getMessage());
    } catch (IOException ex) {
        throw new SignerException(ex.getMessage());
    }

}

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

License:Open Source License

@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
    try {//from www  . j  av a2s. co  m
        Security.addProvider(new BouncyCastleProvider());
        List<Timestamp> listOfTimeStamp = new ArrayList<Timestamp>();
        CMSSignedData cmsSignedData = new CMSSignedData(signature);
        SignerInformationStore signers = cmsSignedData.getSignerInfos();
        Iterator<?> it = signers.getSigners().iterator();
        while (it.hasNext()) {
            SignerInformation signer = (SignerInformation) it.next();
            AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
            Attribute attributeTimeStamp = unsignedAttributes
                    .get(new ASN1ObjectIdentifier(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken.getId()));
            if (attributeTimeStamp != null) {
                TimeStampOperator timeStampOperator = new TimeStampOperator();
                byte[] varTimeStamp = attributeTimeStamp.getAttrValues().getObjectAt(0).toASN1Primitive()
                        .getEncoded();
                TimeStampToken timeStampToken = new TimeStampToken(new CMSSignedData(varTimeStamp));
                Timestamp timeStampSigner = new Timestamp(timeStampToken);
                timeStampOperator.validate(signer.getSignature(), varTimeStamp, null);
                listOfTimeStamp.add(timeStampSigner);
            }
        }
        return listOfTimeStamp;
    } catch (CertificateCoreException | IOException | TSPException | CMSException e) {
        throw new SignerException(e);
    }
}

From source file:org.demoiselle.signer.timestamp.connector.TimeStampOperator.java

License:Open Source License

/**
 * Validate a time stamp/* w w  w  . j  av a2 s .  com*/
 *
 * @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();
            SignerInformationVerifier siv = new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                    .build(cert);
            if (signer.verify(siv)) {
                verified++;
            }
            cert.getExtension(new ASN1ObjectIdentifier("2.5.29.31")).getExtnValue();
            timeStampToken.validate(siv);
        }

        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();
            TimeStampTokenInfo info = timeStampToken.getTimeStampInfo();
            ASN1ObjectIdentifier algOID = info.getMessageImprintAlgOID();
            digest.setAlgorithm(algOID.toString());
            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());
    }
}

From source file:org.dihedron.crypto.operations.verify.pkcs7.PKCS7Verifier.java

License:Open Source License

@SuppressWarnings("unchecked")
private boolean verify(CMSSignedData signed, byte[] data) throws CryptoException {

    try {/* w w  w.j  av a2 s.  co m*/
        logger.debug("starting CMSSignedData verification ... ");

        SignerInformationStore signers = signed.getSignerInfos();
        Store certificates = signed.getCertificates();

        logger.debug("{} signers found", signers.getSigners().size());

        // loop over signers and their respective certificates and check if
        // the signature is verified (no check is made on certificates); exit
        // as soon as a verification fails, otherwise return a sound "verified" 
        for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) {
            logger.debug("{} certificates found for signer '{}'",
                    certificates.getMatches(signer.getSID()).size(), signer.getSID());
            for (Object certificate : certificates.getMatches(signer.getSID())) {
                if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC")
                        .build((X509CertificateHolder) certificate))) {
                    logger.info("signature verified for signer '{}'", signer.getSID());
                } else {
                    logger.error("signature verification failed for signer '{}'", signer.getSID());
                    return false;
                }
            }
        }
        logger.info("all signatures successfully verified");
        return true;
    } catch (OperatorCreationException e) {
        logger.error("error creating operator", e);
        throw new CryptoException("Error creating operator", e);
    } catch (CertificateException e) {
        logger.error("invalid certificate", e);
        throw new CryptoException("Invalid certificate", e);
    } catch (CMSException e) {
        logger.error("CMS error", e);
        throw new CryptoException("CMS error", e);
    }
}

From source file:org.ejbca.batchenrollmentgui.BatchEnrollmentGUIView.java

License:Open Source License

@SuppressWarnings("unchecked")
private static CMSValidationResult validateCMS(final CMSSignedData signedData,
        final Collection<Certificate> trustedCerts) {

    final CMSValidationResult result = new CMSValidationResult();

    try {//  w  w  w  .  j a v a2s. c  om
        final ContentInfo ci = signedData.toASN1Structure();
        if (LOG.isDebugEnabled()) {
            LOG.debug("ci.content: " + ci.getContent() + "\n" + "signedContent: "
                    + signedData.getSignedContent());
        }

        final Object content = signedData.getSignedContent().getContent();

        if (content instanceof byte[]) {
            result.setContent((byte[]) content);
        }

        Store certs = signedData.getCertificates();
        SignerInformationStore signers = signedData.getSignerInfos();
        for (Object o : signers.getSigners()) {
            if (o instanceof SignerInformation) {
                SignerInformation si = (SignerInformation) o;

                if (LOG.isDebugEnabled()) {
                    LOG.debug("*** SIGNATURE: " + "\n" + si.getSID());
                }

                final Collection<X509CertificateHolder> signerCerts = (Collection<X509CertificateHolder>) certs
                        .getMatches(si.getSID());

                if (LOG.isDebugEnabled()) {
                    LOG.debug("signerCerts: " + signerCerts);
                }
                JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
                for (X509CertificateHolder signerCert : signerCerts) {
                    final X509Certificate signerX509Cert = jcaX509CertificateConverter
                            .getCertificate(signerCert);

                    // Verify the signature
                    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
                            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                    boolean consistent = si
                            .verify(jcaSignerInfoVerifierBuilder.build(signerX509Cert.getPublicKey()));
                    if (consistent) {

                        if (LOG.isDebugEnabled()) {
                            LOG.debug((consistent ? "Consistent" : "Inconsistent") + " signature from "
                                    + signerX509Cert.getSubjectDN() + " issued by "
                                    + signerX509Cert.getIssuerDN());
                        }

                        result.setValidSignature(consistent);

                        try {
                            final List<X509Certificate> signerChain = validateChain(signerX509Cert, certs,
                                    trustedCerts);

                            result.setValidChain(true);
                            result.setSignerChain(signerChain);

                            JOptionPane.showMessageDialog(null,
                                    "Found valid signature from \"" + signerX509Cert.getSubjectDN() + "\"",
                                    "Signature check", JOptionPane.INFORMATION_MESSAGE);

                        } catch (CertPathBuilderException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, "Error: Certificate path:\n" + ex.getMessage(),
                                    "Signature check", JOptionPane.ERROR_MESSAGE);
                        } catch (CertPathValidatorException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null,
                                    "Error: Certificate validation:\n" + ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (InvalidAlgorithmParameterException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (NoSuchAlgorithmException ex) {
                            result.setError(ex.getMessage());
                            JOptionPane.showMessageDialog(null, ex.getMessage(), "Signature check",
                                    JOptionPane.ERROR_MESSAGE);
                        } catch (GeneralSecurityException e) {
                            //Crappy catch-all, but not much to do due to underlying BC-code
                            result.setError(e.getMessage());
                            JOptionPane.showMessageDialog(null, e.getMessage(),
                                    "Error: Certificate validation:\n", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        result.setError("Inconsistent signature!");
                        JOptionPane.showMessageDialog(null, "Error: Inconsisten signature!", "Signature check",
                                JOptionPane.ERROR_MESSAGE);
                    }
                }

            }
        }

    } catch (CMSException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (OperatorCreationException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    } catch (CertificateException ex) {
        result.setError(ex.getMessage());
        LOG.error("Parsing and validating CMS", ex);
    }
    return result;
}