Example usage for org.bouncycastle.cms CMSSignedData CMSSignedData

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

Introduction

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

Prototype

public CMSSignedData(Map hashes, ContentInfo sigData) throws CMSException 

Source Link

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/*from   www . j a  va 2 s .  c o  m*/
 *
 * @param content Is only necessary to inform if the PKCS7 package is NOT
 *        ATTACHED type. If it is of type attached, this parameter will be
 *        replaced by the contents of the PKCS7 package.
 * @param signedData Value in bytes of the PKCS7 package, such as the
 *        contents of a ".p7s" file. It is not only signature as in the
 *        case of PKCS1.
 * @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 byte[] doSign(byte[] content, byte[] previewSignature) {
    try {/*from w w  w  .java 2s.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.roda.common.certification.SignatureUtility.java

/**
 * Verify detached signature//  ww  w . ja  v  a2 s .c om
 * 
 * @param file
 * @param signature
 * @return true if valid
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws CMSException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws CertificateException
 * @throws OperatorCreationException
 */
public boolean verify(File file, File signature)
        throws NoSuchAlgorithmException, NoSuchProviderException, CertStoreException, CMSException,
        FileNotFoundException, IOException, CertificateException, OperatorCreationException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData signedData = new CMSSignedData(cmsFile, new FileInputStream(signature));

    return verifySignatures(signedData, null);
}

From source file:org.roda.core.plugins.plugins.characterization.SignatureUtility.java

/**
 * Verify detached signature/*  ww w.  jav  a 2  s.  c o  m*/
 * 
 * @param file
 * @param signature
 * @return true if valid
 * @throws NoSuchAlgorithmException
 * @throws NoSuchProviderException
 * @throws CertStoreException
 * @throws CMSException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws CertificateException
 */
public boolean verify(File file, File signature) throws FileNotFoundException, CMSException,
        CertificateException, NoSuchAlgorithmException, NoSuchProviderException {
    CMSProcessableFile cmsFile = new CMSProcessableFile(file);
    CMSSignedData signedData = new CMSSignedData(cmsFile, new FileInputStream(signature));
    return verifySignatures(signedData, null);
}

From source file:org.votingsystem.signature.dnie.DNIePDFContentSigner.java

License:Open Source License

public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate,
        Provider sigProvider, boolean addDefaultAttributes, List signerInfs) throws Exception {
    // TODO if (signerInfs.isEmpty()){
    //            /* RFC 3852 5.2
    //             * "In the degenerate case where there are no signers, the
    //             * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
    //             * case, the content type within the EncapsulatedContentInfo value being
    //             * "signed" MUST be id-data (as defined in section 4), and the content
    //             * field of the EncapsulatedContentInfo value MUST be omitted."
    //             *//*w w w .j av  a  2 s .  c  o  m*/
    //            if (encapsulate) {
    //                throw new IllegalArgumentException("no signers, encapsulate must be false");
    //            } if (!DATA.equals(eContentType)) {
    //                throw new IllegalArgumentException("no signers, eContentType must be id-data");
    //            }
    //        }
    //        if (!DATA.equals(eContentType)) {
    //            /* RFC 3852 5.3
    //             * [The 'signedAttrs']...
    //             * field is optional, but it MUST be present if the content type of
    //             * the EncapsulatedContentInfo value being signed is not id-data.
    //             */
    //            // TODO signedAttrs must be present for all signers
    //        }
    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    digests.clear(); // clear the current preserved digest state
    Iterator it = _signers.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID()));
        signerInfos.add(signer.toSignerInfo());
    }
    boolean isCounterSignature = (eContentType == null);
    ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data
            : new ASN1ObjectIdentifier(eContentType);
    it = signerInfs.iterator();
    while (it.hasNext()) {
        SignerInf signer = (SignerInf) it.next();
        log.info("signer.signerIdentifier: " + signer.signerIdentifier.toASN1Object().toString());
        digestAlgs.add(signer.getDigestAlgorithmID());
        signerInfos.add(signer.toSignerInfo(contentTypeOID, content, rand, null, addDefaultAttributes,
                isCounterSignature));
    }
    ASN1Set certificates = null;
    if (!certs.isEmpty())
        certificates = CMSUtils.createBerSetFromList(certs);
    ASN1Set certrevlist = null;
    if (!crls.isEmpty())
        certrevlist = CMSUtils.createBerSetFromList(crls);
    ASN1OctetString octs = null;
    if (encapsulate && content != null) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        content.write(bOut);
        octs = new BERConstructedOctetString(bOut.toByteArray());
    }
    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}

From source file:org.votingsystem.signature.util.PDFContentSigner.java

License:Open Source License

public CMSSignedData getCMSSignedData(String eContentType, CMSProcessable content, boolean encapsulate,
        Provider sigProvider, boolean addDefaultAttributes, List<SignerInfo> signerInfoList)
        throws NoSuchAlgorithmException, CMSException, Exception {
    // TODO if (signerInfs.isEmpty()){
    //            /* RFC 3852 5.2
    //             * "In the degenerate case where there are no signers, the
    //             * EncapsulatedContentInfo value being "signed" is irrelevant.  In this
    //             * case, the content type within the EncapsulatedContentInfo value being
    //             * "signed" MUST be id-data (as defined in section 4), and the content
    //             * field of the EncapsulatedContentInfo value MUST be omitted."
    //             */// ww  w  .j  a v  a2 s .c  om
    //            if (encapsulate) {
    //                throw new IllegalArgumentException("no signers, encapsulate must be false");
    //            } if (!DATA.equals(eContentType)) {
    //                throw new IllegalArgumentException("no signers, eContentType must be id-data");
    //            }
    //        }
    //        if (!DATA.equals(eContentType)) {
    //            /* RFC 3852 5.3
    //             * [The 'signedAttrs']...
    //             * field is optional, but it MUST be present if the content type of
    //             * the EncapsulatedContentInfo value being signed is not id-data.
    //             */
    //            // TODO signedAttrs must be present for all signers
    //        }
    ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
    ASN1EncodableVector signerInfos = new ASN1EncodableVector();
    digests.clear(); // clear the current preserved digest state
    Iterator it = _signers.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        digestAlgs.add(CMSUtils.fixAlgID(signer.getDigestAlgorithmID()));
        signerInfos.add(signer.toSignerInfo());
    }
    boolean isCounterSignature = (eContentType == null);
    ASN1ObjectIdentifier contentTypeOID = isCounterSignature ? CMSObjectIdentifiers.data
            : new ASN1ObjectIdentifier(eContentType);
    for (SignerInfo signerInfo : signerInfoList) {
        digestAlgs.add(signerInfo.getDigestAlgorithm());
        signerInfos.add(signerInfo);
    }
    ASN1Set certificates = null;
    if (!certs.isEmpty())
        certificates = CMSUtils.createBerSetFromList(certs);
    ASN1Set certrevlist = null;
    if (!crls.isEmpty())
        certrevlist = CMSUtils.createBerSetFromList(crls);
    ASN1OctetString octs = null;
    if (encapsulate && content != null) {
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();
        content.write(bOut);
        octs = new BERConstructedOctetString(bOut.toByteArray());
    }
    ContentInfo encInfo = new ContentInfo(contentTypeOID, octs);
    SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, certificates, certrevlist,
            new DERSet(signerInfos));
    ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
    return new CMSSignedData(content, contentInfo);
}

From source file:org.xwiki.crypto.signer.internal.cms.BcCMSUtils.java

License:Open Source License

/**
 * Build a Bouncy Castle {@link CMSSignedData} from bytes.
 *
 * @param signature the signature.//from   w  ww.j a  v a  2 s  .c o m
 * @param data the data signed.
 * @return a CMS signed data.
 * @throws GeneralSecurityException if the signature could not be decoded.
 */
public static CMSSignedData getSignedData(byte[] signature, byte[] data) throws GeneralSecurityException {
    CMSSignedData signedData;
    try {
        if (data != null) {
            signedData = new CMSSignedData(new CMSProcessableByteArray(data), signature);
        } else {
            signedData = new CMSSignedData(signature);
        }
    } catch (CMSException e) {
        throw new GeneralSecurityException("Unable to decode signature", e);
    }
    return signedData;
}

From source file:org.xwiki.crypto.x509.internal.X509SignatureService.java

License:Open Source License

/**
 * {@inheritDoc}/*from   w ww.  j a  v  a  2 s .c  o  m*/
 *
 * @see org.xwiki.crypto.CryptoService#verifyText(java.lang.String, java.lang.String)
 */
public XWikiX509Certificate verifyText(String signedText, String base64Signature)
        throws GeneralSecurityException {
    try {
        byte[] data = signedText.getBytes();
        byte[] signature = Convert.fromBase64String(base64Signature);
        CMSSignedData cmsData = new CMSSignedData(new CMSProcessableByteArray(data), signature);
        CertStore certStore = cmsData.getCertificatesAndCRLs(CERT_STORE_TYPE, PROVIDER);
        SignerInformationStore signers = cmsData.getSignerInfos();

        int numSigners = signers.getSigners().size();
        if (numSigners != 1) {
            throw new GeneralSecurityException("Only one signature is supported, found " + numSigners);
        }
        XWikiX509Certificate result = null;
        for (Iterator<?> it = signers.getSigners().iterator(); it.hasNext();) {
            if (result != null) {
                throw new GeneralSecurityException("Only one certificate is supported");
            }
            SignerInformation signer = (SignerInformation) it.next();
            Collection<? extends Certificate> certs = certStore.getCertificates(signer.getSID());
            for (Iterator<? extends Certificate> cit = certs.iterator(); cit.hasNext();) {
                Certificate certificate = cit.next();
                if (!signer.verify(certificate.getPublicKey(), PROVIDER)) {
                    return null;
                }
                if (certificate instanceof X509Certificate) {
                    result = new XWikiX509Certificate((X509Certificate) certificate, null);
                }
            }
        }
        return result;
    } catch (CMSException exception) {
        // This means the text is invalid, our contract says we return null.
        // This message is hardcoded in org.bouncycastle.cms.SignerInformation
        if ("message-digest attribute value does not match calculated value".equals(exception.getMessage())) {
            return null;
        }
        throw new GeneralSecurityException(exception);
    } catch (Exception exception) {
        throw new GeneralSecurityException(exception);
    }
}

From source file:pdfbox.SignatureVerifier.java

License:Apache License

/**
 * Verify a PKCS7 signature.//from www  .j  a v  a  2s . c  om
 *
 * @param byteArray the byte sequence that has been signed
 * @param contents the /Contents field as a COSString
 * @param sig the PDF signature (the /V dictionary)
 * @throws CertificateException
 * @throws CMSException
 * @throws StoreException
 * @throws OperatorCreationException
 */
private SignatureResult verifyPKCS7(byte[] byteArray, COSString contents, PDSignature sig)
        throws CMSException, CertificateException, StoreException, OperatorCreationException {
    // inspiration:
    // http://stackoverflow.com/a/26702631/535646
    // http://stackoverflow.com/a/9261365/535646
    CMSProcessable signedContent = new CMSProcessableByteArray(byteArray);
    CMSSignedData signedData = new CMSSignedData(signedContent, contents.getBytes());
    Store certificatesStore = signedData.getCertificates();
    Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
    SignerInformation signerInformation = signers.iterator().next();
    Collection matches = certificatesStore.getMatches(signerInformation.getSID());
    X509CertificateHolder certificateHolder = (X509CertificateHolder) matches.iterator().next();
    X509Certificate certFromSignedData = new JcaX509CertificateConverter().getCertificate(certificateHolder);
    //System.out.println("certFromSignedData: " + certFromSignedData);
    certFromSignedData.checkValidity(sig.getSignDate().getTime());

    JcaSimpleSignerInfoVerifierBuilder verifierBuilder = new JcaSimpleSignerInfoVerifierBuilder();
    if (provider != null) {
        verifierBuilder.setProvider(provider);
    }

    boolean validated = false;
    try {
        validated = signerInformation.verify(verifierBuilder.build(certFromSignedData));

    } catch (CMSSignerDigestMismatchException e) {
        System.out.println("Signature failed to validate: ");
        e.printStackTrace();
    }

    return new SignatureResult(certFromSignedData, validated);
}

From source file:test.unit.be.fedict.eid.applet.service.signer.CMSTest.java

License:Open Source License

/**
 * CMS signature with external data and external certificate. The CMS only
 * contains the signature and some certificate selector.
 * //from  www  . j a v a 2  s . c o m
 * @throws Exception
 */
@Test
public void testBasicCmsSignature() throws Exception {
    // setup
    KeyPair keyPair = PkiTestUtils.generateKeyPair();
    DateTime notBefore = new DateTime();
    DateTime notAfter = notBefore.plusMonths(1);
    X509Certificate certificate = generateSelfSignedCertificate(keyPair, "CN=Test", notBefore, notAfter);
    byte[] toBeSigned = "hello world".getBytes();

    // operate
    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    generator.addSigner(keyPair.getPrivate(), certificate, CMSSignedDataGenerator.DIGEST_SHA1);
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);
    CMSSignedData signedData = generator.generate(content, false, (String) null);

    byte[] cmsSignature = signedData.getEncoded();
    LOG.debug("CMS signature: " + ASN1Dump.dumpAsString(new ASN1StreamParser(cmsSignature).readObject()));

    // verify
    signedData = new CMSSignedData(content, cmsSignature);
    SignerInformationStore signers = signedData.getSignerInfos();
    Iterator<SignerInformation> iter = signers.getSigners().iterator();
    while (iter.hasNext()) {
        SignerInformation signer = iter.next();
        SignerId signerId = signer.getSID();
        LOG.debug("signer: " + signerId);
        assertTrue(signerId.match(certificate));
        assertTrue(signer.verify(keyPair.getPublic(), BouncyCastleProvider.PROVIDER_NAME));
    }
    LOG.debug("content type: " + signedData.getSignedContentTypeOID());
}