Example usage for org.bouncycastle.cms SignerInformation getUnsignedAttributes

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

Introduction

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

Prototype

public AttributeTable getUnsignedAttributes() 

Source Link

Document

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

Usage

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

License:Open Source License

private byte[] doSign(byte[] content, byte[] previewSignature) {
    try {// w  w  w .j a v  a 2 s.  com
        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.CAdESTimeStampSigner.java

License:Open Source License

@Override
public List<Timestamp> checkTimeStampOnSignature(byte[] signature) {
    try {//from www.j  a  v  a2s .  c  o 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.votingsystem.signature.smime.SMIMEMessage.java

License:Open Source License

public void setTimeStampToken(TimeStampToken timeStampToken) throws Exception {
    if (timeStampToken == null)
        throw new Exception("timestamp token null");
    DERObject derObject = new ASN1InputStream(timeStampToken.getEncoded()).readObject();
    DERSet derset = new DERSet(derObject);
    Attribute timeStampAsAttribute = new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, derset);
    Hashtable hashTable = new Hashtable();
    hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute);
    AttributeTable timeStampAsAttributeTable = new AttributeTable(hashTable);
    byte[] timeStampTokenHash = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
    Iterator<SignerInformation> it = smimeSigned.getSignerInfos().getSigners().iterator();
    List<SignerInformation> newSigners = new ArrayList<SignerInformation>();
    while (it.hasNext()) {
        SignerInformation signer = it.next();
        byte[] digestBytes = CMSUtils.getSignerDigest(signer);
        if (Arrays.equals(timeStampTokenHash, digestBytes)) {
            log.info("setTimeStampToken - found signer");
            AttributeTable attributeTable = signer.getUnsignedAttributes();
            SignerInformation updatedSigner = null;
            if (attributeTable != null) {
                log.info("setTimeStampToken - signer with UnsignedAttributes");
                hashTable = attributeTable.toHashtable();
                hashTable.put(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken, timeStampAsAttribute);
                timeStampAsAttributeTable = new AttributeTable(hashTable);
            }//from   w w  w  .j  a  v a  2s.c  o m
            updatedSigner = signer.replaceUnsignedAttributes(signer, timeStampAsAttributeTable);
            newSigners.add(updatedSigner);
        } else
            newSigners.add(signer);
    }
    SignerInformationStore newSignersStore = new SignerInformationStore(newSigners);
    CMSSignedData cmsdata = smimeSigned.replaceSigners(smimeSigned, newSignersStore);
    replaceSigners(cmsdata);
}

From source file:org.votingsystem.signature.smime.SMIMEMessage.java

License:Open Source License

private TimeStampToken checkTimeStampToken(SignerInformation signer) throws Exception {
    TimeStampToken timeStampToken = null;
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
    if (unsignedAttributes != null) {
        Attribute timeStampAttribute = unsignedAttributes
                .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
        if (timeStampAttribute != null) {
            DEREncodable dob = timeStampAttribute.getAttrValues().getObjectAt(0);
            CMSSignedData signedData = new CMSSignedData(dob.getDERObject().getEncoded());
            timeStampToken = new TimeStampToken(signedData);
            return timeStampToken;
        }/*from   www .j av a2s  . c o m*/
    } else
        log.info("checkTimeStampToken - without unsignedAttributes");
    return timeStampToken;
}

From source file:org.xipki.pki.scep.message.DecodedPkiMessage.java

License:Open Source License

@SuppressWarnings("unchecked")
public static DecodedPkiMessage decode(final CMSSignedData pkiMessage, final EnvelopedDataDecryptor recipient,
        final CollectionStore<X509CertificateHolder> certStore) throws MessageDecodingException {
    ParamUtil.requireNonNull("pkiMessage", pkiMessage);
    ParamUtil.requireNonNull("recipient", recipient);

    SignerInformationStore signerStore = pkiMessage.getSignerInfos();
    Collection<SignerInformation> signerInfos = signerStore.getSigners();
    if (signerInfos.size() != 1) {
        throw new MessageDecodingException("number of signerInfos is not 1, but " + signerInfos.size());
    }/* w w w . j ava2  s .co m*/

    SignerInformation signerInfo = signerInfos.iterator().next();
    SignerId sid = signerInfo.getSID();

    Collection<?> signedDataCerts = null;
    if (certStore != null) {
        signedDataCerts = certStore.getMatches(sid);
    }

    if (signedDataCerts == null || signedDataCerts.isEmpty()) {
        signedDataCerts = pkiMessage.getCertificates().getMatches(signerInfo.getSID());
    }

    if (signedDataCerts == null || signedDataCerts.size() != 1) {
        throw new MessageDecodingException("could not find embedded certificate to verify the signature");
    }

    AttributeTable signedAttrs = signerInfo.getSignedAttributes();
    if (signedAttrs == null) {
        throw new MessageDecodingException("missing SCEP attributes");
    }

    Date signingTime = null;
    // signingTime
    ASN1Encodable attrValue = ScepUtil.getFirstAttrValue(signedAttrs, CMSAttributes.signingTime);
    if (attrValue != null) {
        signingTime = Time.getInstance(attrValue).getDate();
    }

    // transactionId
    String str = getPrintableStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_TRANSACTION_ID);
    if (str == null || str.isEmpty()) {
        throw new MessageDecodingException("missing required SCEP attribute transactionId");
    }
    TransactionId transactionId = new TransactionId(str);

    // messageType
    Integer intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_MESSAGE_TYPE);
    if (intValue == null) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": missing required SCEP attribute messageType");
    }

    MessageType messageType;
    try {
        messageType = MessageType.forValue(intValue);
    } catch (IllegalArgumentException ex) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": invalid messageType '" + intValue + "'");
    }

    // senderNonce
    Nonce senderNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_SENDER_NONCE);
    if (senderNonce == null) {
        throw new MessageDecodingException(
                "tid " + transactionId.getId() + ": missing required SCEP attribute senderNonce");
    }

    DecodedPkiMessage ret = new DecodedPkiMessage(transactionId, messageType, senderNonce);
    if (signingTime != null) {
        ret.setSigningTime(signingTime);
    }

    Nonce recipientNonce = null;
    try {
        recipientNonce = getNonceAttrValue(signedAttrs, ScepObjectIdentifiers.ID_RECIPIENT_NONCE);
    } catch (MessageDecodingException ex) {
        ret.setFailureMessage("could not parse recipientNonce: " + ex.getMessage());
    }

    if (recipientNonce != null) {
        ret.setRecipientNonce(recipientNonce);
    }

    PkiStatus pkiStatus = null;
    FailInfo failInfo = null;
    if (MessageType.CertRep == messageType) {
        // pkiStatus
        try {
            intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_PKI_STATUS);
        } catch (MessageDecodingException ex) {
            ret.setFailureMessage("could not parse pkiStatus: " + ex.getMessage());
            return ret;
        }

        if (intValue == null) {
            ret.setFailureMessage("missing required SCEP attribute pkiStatus");
            return ret;
        }

        try {
            pkiStatus = PkiStatus.forValue(intValue);
        } catch (IllegalArgumentException ex) {
            ret.setFailureMessage("invalid pkiStatus '" + intValue + "'");
            return ret;
        }
        ret.setPkiStatus(pkiStatus);

        // failureInfo
        if (pkiStatus == PkiStatus.FAILURE) {
            try {
                intValue = getIntegerPrintStringAttrValue(signedAttrs, ScepObjectIdentifiers.ID_FAILINFO);
            } catch (MessageDecodingException ex) {
                ret.setFailureMessage("could not parse failInfo: " + ex.getMessage());
                return ret;
            }

            if (intValue == null) {
                ret.setFailureMessage("missing required SCEP attribute failInfo");
                return ret;
            }

            try {
                failInfo = FailInfo.forValue(intValue);
            } catch (IllegalArgumentException ex) {
                ret.setFailureMessage("invalid failInfo '" + intValue + "'");
                return ret;
            }

            ret.setFailInfo(failInfo);
        } // end if(pkiStatus == PkiStatus.FAILURE)
    } // end if (MessageType.CertRep == messageType)

    // other signedAttributes
    Attribute[] attrs = signedAttrs.toASN1Structure().getAttributes();
    for (Attribute attr : attrs) {
        ASN1ObjectIdentifier type = attr.getAttrType();
        if (!SCEP_ATTR_TYPES.contains(type)) {
            ret.addSignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }

    // unsignedAttributes
    AttributeTable unsignedAttrs = signerInfo.getUnsignedAttributes();
    attrs = (unsignedAttrs == null) ? null : unsignedAttrs.toASN1Structure().getAttributes();
    if (attrs != null) {
        for (Attribute attr : attrs) {
            ASN1ObjectIdentifier type = attr.getAttrType();
            ret.addUnsignendAttribute(type, attr.getAttrValues().getObjectAt(0));
        }
    }

    ASN1ObjectIdentifier digestAlgOid = signerInfo.getDigestAlgorithmID().getAlgorithm();
    ret.setDigestAlgorithm(digestAlgOid);

    String sigAlgOid = signerInfo.getEncryptionAlgOID();
    if (!PKCSObjectIdentifiers.rsaEncryption.getId().equals(sigAlgOid)) {
        ASN1ObjectIdentifier tmpDigestAlgOid;
        try {
            tmpDigestAlgOid = ScepUtil.extractDigesetAlgorithmIdentifier(signerInfo.getEncryptionAlgOID(),
                    signerInfo.getEncryptionAlgParams());
        } catch (Exception ex) {
            final String msg = "could not extract digest algorithm from signerInfo.signatureAlgorithm: "
                    + ex.getMessage();
            LOG.error(msg);
            LOG.debug(msg, ex);
            ret.setFailureMessage(msg);
            return ret;
        }
        if (!digestAlgOid.equals(tmpDigestAlgOid)) {
            ret.setFailureMessage(
                    "digestAlgorithm and encryptionAlgorithm do not use the" + " same digestAlgorithm");
            return ret;
        } // end if
    } // end if

    X509CertificateHolder tmpSignerCert = (X509CertificateHolder) signedDataCerts.iterator().next();
    X509Certificate signerCert;
    try {
        signerCert = ScepUtil.toX509Cert(tmpSignerCert.toASN1Structure());
    } catch (CertificateException ex) {
        final String msg = "could not construct X509Certificate: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }
    ret.setSignatureCert(signerCert);

    // validate the signature
    SignerInformationVerifier verifier;
    try {
        verifier = new JcaSimpleSignerInfoVerifierBuilder().build(signerCert.getPublicKey());
    } catch (OperatorCreationException ex) {
        final String msg = "could not build signature verifier: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    boolean signatureValid;
    try {
        signatureValid = signerInfo.verify(verifier);
    } catch (CMSException ex) {
        final String msg = "could not verify the signature: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setSignatureValid(signatureValid);
    if (!signatureValid) {
        return ret;
    }

    if (MessageType.CertRep == messageType
            && (pkiStatus == PkiStatus.FAILURE | pkiStatus == PkiStatus.PENDING)) {
        return ret;
    }

    // MessageData
    CMSTypedData signedContent = pkiMessage.getSignedContent();
    ASN1ObjectIdentifier signedContentType = signedContent.getContentType();
    if (!CMSObjectIdentifiers.envelopedData.equals(signedContentType)) {
        // fall back: some SCEP client, such as JSCEP use id-data
        if (!CMSObjectIdentifiers.data.equals(signedContentType)) {
            ret.setFailureMessage(
                    "either id-envelopedData or id-data is excepted, but not '" + signedContentType.getId());
            return ret;
        }
    }

    CMSEnvelopedData envData;
    try {
        envData = new CMSEnvelopedData((byte[]) signedContent.getContent());
    } catch (CMSException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    ret.setContentEncryptionAlgorithm(envData.getContentEncryptionAlgorithm().getAlgorithm());
    byte[] encodedMessageData;
    try {
        encodedMessageData = recipient.decrypt(envData);
    } catch (MessageDecodingException ex) {
        final String msg = "could not create the CMSEnvelopedData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);

        ret.setDecryptionSuccessful(false);
        return ret;
    }

    ret.setDecryptionSuccessful(true);

    try {
        if (MessageType.PKCSReq == messageType || MessageType.RenewalReq == messageType
                || MessageType.UpdateReq == messageType) {
            CertificationRequest messageData = CertificationRequest.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertPoll == messageType) {
            IssuerAndSubject messageData = IssuerAndSubject.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
        } else if (MessageType.GetCert == messageType || MessageType.GetCRL == messageType) {
            IssuerAndSerialNumber messageData = IssuerAndSerialNumber.getInstance(encodedMessageData);
            ret.setMessageData(messageData);
            ret.setMessageData(messageData);
        } else if (MessageType.CertRep == messageType) {
            ContentInfo ci = ContentInfo.getInstance(encodedMessageData);
            ret.setMessageData(ci);
        } else {
            throw new RuntimeException("should not reach here, unknown messageType " + messageType);
        }
    } catch (Exception ex) {
        final String msg = "could not parse the messageData: " + ex.getMessage();
        LOG.error(msg);
        LOG.debug(msg, ex);
        ret.setFailureMessage(msg);
        return ret;
    }

    return ret;
}

From source file:se.tillvaxtverket.ttsigvalws.ttwssigvalidation.pdf.PdfSignatureVerifier.java

License:Open Source License

private static void checkTimestamps(CMSSignedDataParser sp, CMSSigVerifyResult sigResult) throws CMSException {
    List<TimeStampResult> timeStampResultList = sigResult.getTimStampResultList();
    sigResult.setTimStampResultList(timeStampResultList);
    SignerInformationStore signers = sp.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();//from   w  ww  .  j ava2  s .co m
    if (!it.hasNext()) {
        return;
    }
    SignerInformation signer = (SignerInformation) it.next();

    //Collect and check time stamps
    AttributeTable unsignedAttributes = signer.getUnsignedAttributes();
    if (unsignedAttributes == null) {
        return;
    }
    ASN1EncodableVector timeStamps = unsignedAttributes
            .getAll(new ASN1ObjectIdentifier("1.2.840.113549.1.9.16.2.14"));
    if (timeStamps.size() == 0) {
        return;
    }
    for (int i = 0; i < timeStamps.size(); i++) {
        try {
            Attribute timestampAttr = Attribute.getInstance(timeStamps.get(i));
            byte[] timeStampBytes = timestampAttr.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded();
            TimeStampResult tsResult = new TimeStampResult();
            tsResult.setTimestamp(timeStampBytes);
            timeStampResultList.add(tsResult);

            InputStream tsis = new ByteArrayInputStream(timeStampBytes);
            CMSSignedDataParser tsSp = new CMSSignedDataParser(new BcDigestCalculatorProvider(), tsis);

            byte[] tsInfoBytes = IOUtils.toByteArray(tsSp.getSignedContent().getContentStream());
            TimeStampData timeStampData = PdfBoxSigUtil.getTimeStampData(tsInfoBytes);
            tsResult.setTsData(timeStampData);

            //Compare TimeStamp data hash with signature hash
            byte[] sigHash = getDigest(timeStampData.getImprintHashAlgo(), signer.getSignature());
            tsResult.setTimestampMatch(Arrays.equals(sigHash, timeStampData.getImprintDigest()));

            CMSSigVerifyResult tsSigResult = new CMSSigVerifyResult();
            tsSigResult.setSignedData(timeStampBytes);
            tsResult.setSignatureVerification(tsSigResult);

            verifyCMSSignature(tsSp, tsSigResult);
        } catch (Exception e) {
        }

    }
    sigResult.setTimStampResultList(timeStampResultList);
}