Example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificate

List of usage examples for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificate

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificate.

Prototype

ASN1ObjectIdentifier id_aa_signingCertificate

To view the source code for org.bouncycastle.asn1.pkcs PKCSObjectIdentifiers id_aa_signingCertificate.

Click Source Link

Document

PKCS#9: 1.2.840.113549.1.9.16.2.12

Usage

From source file:be.apsu.extremon.probes.tsp.TSPProbe.java

License:Open Source License

public void probe_forever() {
    double start = 0, end = 0;
    BigInteger requestNonce;/*from w w w.  j  a va 2s . co  m*/
    byte[] requestHashedMessage = new byte[20];
    List<String> comments = new ArrayList<String>();
    STATE result = STATE.OK;

    log("running");

    this.running = true;
    while (this.running) {
        comments.clear();
        this.random.nextBytes(requestHashedMessage);
        requestNonce = new BigInteger(512, this.random);
        TimeStampRequest request = requestGenerator.generate(TSPAlgorithms.SHA1, requestHashedMessage,
                requestNonce);

        end = 0;
        start = System.currentTimeMillis();

        try {
            TimeStampResponse response = probe(request);

            switch (response.getStatus()) {
            case PKIStatus.GRANTED:
                comments.add("granted");
                result = STATE.OK;
                break;
            case PKIStatus.GRANTED_WITH_MODS:
                comments.add("granted with modifications");
                result = STATE.WARNING;
                break;
            case PKIStatus.REJECTION:
                comments.add("rejected");
                result = STATE.ALERT;
                break;
            case PKIStatus.WAITING:
                comments.add("waiting");
                result = STATE.ALERT;
                break;
            case PKIStatus.REVOCATION_WARNING:
                comments.add("revocation warning");
                result = STATE.WARNING;
                break;
            case PKIStatus.REVOCATION_NOTIFICATION:
                comments.add("revocation notification");
                result = STATE.ALERT;
                break;
            default:
                comments.add("response outside RFC3161");
                result = STATE.ALERT;
                break;
            }

            if (response.getStatus() >= 2)
                comments.add(response.getFailInfo() != null ? response.getFailInfo().getString()
                        : "(missing failinfo)");

            if (response.getStatusString() != null)
                comments.add(response.getStatusString());

            end = System.currentTimeMillis();
            TimeStampToken timestampToken = response.getTimeStampToken();

            timestampToken.validate(this.signerVerifier);
            comments.add("validated");

            AttributeTable table = timestampToken.getSignedAttributes();
            TimeStampTokenInfo tokenInfo = timestampToken.getTimeStampInfo();
            BigInteger responseNonce = tokenInfo.getNonce();
            byte[] responseHashedMessage = tokenInfo.getMessageImprintDigest();
            long genTimeSeconds = (tokenInfo.getGenTime().getTime()) / 1000;
            long currentTimeSeconds = (long) (start + ((end - start) / 2)) / 1000;

            put("clockskew", (genTimeSeconds - currentTimeSeconds) * 1000);

            if (Math.abs((genTimeSeconds - currentTimeSeconds)) > 1) {
                comments.add("clock skew > 1s");
                result = STATE.ALERT;
            }

            Store responseCertificatesStore = timestampToken.toCMSSignedData().getCertificates();
            @SuppressWarnings("unchecked")
            Collection<X509CertificateHolder> certs = responseCertificatesStore.getMatches(null);
            for (X509CertificateHolder certificate : certs) {
                AlgorithmIdentifier sigalg = certificate.getSignatureAlgorithm();
                if (!(oidsAllowed.contains(sigalg.getAlgorithm().getId()))) {
                    String cleanDn = certificate.getSubject().toString().replace("=", ":");
                    comments.add("signature cert \"" + cleanDn + "\" signed using "
                            + getName(sigalg.getAlgorithm().getId()));
                    result = STATE.ALERT;
                }
            }

            if (!responseNonce.equals(requestNonce)) {
                comments.add("nonce modified");
                result = STATE.ALERT;
            }

            if (!Arrays.equals(responseHashedMessage, requestHashedMessage)) {
                comments.add("hashed message modified");
                result = STATE.ALERT;
            }

            if (table.get(PKCSObjectIdentifiers.id_aa_signingCertificate) == null) {
                comments.add("signingcertificate missing");
                result = STATE.ALERT;
            }
        } catch (TSPException tspEx) {
            comments.add("validation failed");
            comments.add("tspexception-" + tspEx.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (IOException iox) {
            comments.add("unable to obtain response");
            comments.add("ioexception-" + iox.getMessage().toLowerCase());
            result = STATE.ALERT;
        } catch (Exception ex) {
            comments.add("unhandled exception");
            result = STATE.ALERT;
        } finally {
            if (end == 0)
                end = System.currentTimeMillis();
        }

        put(RESULT_SUFFIX, result);
        put(RESULT_COMMENT_SUFFIX, StringUtils.join(comments, "|"));
        put("responsetime", (end - start));

        try {
            Thread.sleep(this.delay);
        } catch (InterruptedException ex) {
            log("interrupted");
        }
    }
}

From source file:de.rub.dez6a3.jpdfsigner.TimeStampToken.java

License:Open Source License

public TimeStampToken(CMSSignedData signedData) throws TSPException, IOException {
    this.tsToken = signedData;

    if (!this.tsToken.getSignedContentTypeOID().equals(PKCSObjectIdentifiers.id_ct_TSTInfo.getId())) {
        throw new TSPValidationException("ContentInfo object not for a time stamp.");
    }//from  ww  w.j  a  v  a2s. c om

    Collection signers = tsToken.getSignerInfos().getSigners();

    if (signers.size() != 1) {
        throw new IllegalArgumentException("Time-stamp token signed by " + signers.size()
                + " signers, but it must contain just the TSA signature.");
    }

    tsaSignerInfo = (SignerInformation) signers.iterator().next();

    try {
        CMSProcessable content = tsToken.getSignedContent();
        ByteArrayOutputStream bOut = new ByteArrayOutputStream();

        content.write(bOut);

        ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bOut.toByteArray()));

        this.tstInfo = new TimeStampTokenInfo(TSTInfo.getInstance(aIn.readObject()));

        Attribute attr = tsaSignerInfo.getSignedAttributes()
                .get(PKCSObjectIdentifiers.id_aa_signingCertificate);

        if (attr == null) {
            throw new TSPValidationException("no signing certificate attribute found, time stamp invalid.");
        }

        SigningCertificate signCert = SigningCertificate.getInstance(attr.getAttrValues().getObjectAt(0));

        this.certID = ESSCertID.getInstance(signCert.getCerts()[0]);
    } catch (CMSException e) {
        throw new TSPException(e.getMessage(), e.getUnderlyingException());
    }
}

From source file:es.gob.afirma.envelopers.cades.CAdESUtils.java

License:Open Source License

/** M&eacute;todo que genera la parte que contiene la informaci&oacute;n del
 * Usuario. Se generan los atributos que se necesitan para generar la firma.
 * @param cert Certificado del firmante//  w  w w.  j av a2s  .  c o m
 * @param datos Datos firmados
 * @param policy Pol&iacute;tica de firma
 * @param messageDigest
 * @return Los datos necesarios para generar la firma referente a los datos
 *         del usuario.
 * @throws java.security.NoSuchAlgorithmException
 * @throws java.io.IOException
 * @throws CertificateEncodingException */
static ASN1EncodableVector generateSignerInfo(final X509Certificate cert, final String digestAlgorithmName,
        final byte[] datos, final AdESPolicy policy, final byte[] messageDigest)
        throws NoSuchAlgorithmException, IOException, CertificateEncodingException {

    // ALGORITMO DE HUELLA DIGITAL
    final AlgorithmIdentifier digestAlgorithmOID = SigUtils
            .makeAlgId(AOAlgorithmID.getOID(digestAlgorithmName));

    // // ATRIBUTOS

    // authenticatedAttributes
    final ASN1EncodableVector contexExpecific = initContexExpecific(digestAlgorithmName, datos,
            PKCSObjectIdentifiers.data.getId(), messageDigest);

    // Serial Number
    // comentar lo de abajo para version del rfc 3852
    contexExpecific.add(new Attribute(RFC4519Style.serialNumber,
            new DERSet(new DERPrintableString(cert.getSerialNumber().toString()))));

    if (!"SHA1".equals(AOSignConstants.getDigestAlgorithmName(digestAlgorithmName))) { //$NON-NLS-1$

        //********************************************/
        //***** La Nueva operatividad esta comentada */
        //********************************************/
        // INICIO SINGING CERTIFICATE-V2

        /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
         * CertificateSerialNumber */

        final TBSCertificateStructure tbs = TBSCertificateStructure
                .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate()));

        /** ESSCertIDv2 ::= SEQUENCE { hashAlgorithm AlgorithmIdentifier
         * DEFAULT {algorithm id-sha256}, certHash Hash, issuerSerial
         * IssuerSerial OPTIONAL }
         * Hash ::= OCTET STRING */

        final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded());
        final ESSCertIDv2[] essCertIDv2 = { new ESSCertIDv2(digestAlgorithmOID, certHash,
                new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())), tbs.getSerialNumber())) };

        /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
         * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
         * OPTIONAL }
         * CertPolicyId ::= OBJECT IDENTIFIER
         * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
         * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

        final SigningCertificateV2 scv2;
        if (policy.getPolicyIdentifier() != null) {

            /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
             * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
             * } */
            scv2 = new SigningCertificateV2(essCertIDv2, getPolicyInformation(policy)); // con
            // politica
        } else {
            scv2 = new SigningCertificateV2(essCertIDv2); // Sin politica
        }

        // Secuencia con singningCertificate
        contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2)));

        // FIN SINGING CERTIFICATE-V2

    } else {

        // INICIO SINGNING CERTIFICATE

        /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
         * CertificateSerialNumber } */

        final TBSCertificateStructure tbs = TBSCertificateStructure
                .getInstance(ASN1Primitive.fromByteArray(cert.getTBSCertificate()));

        final IssuerSerial isuerSerial = new IssuerSerial(new GeneralNames(new GeneralName(tbs.getIssuer())),
                tbs.getSerialNumber());

        /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
         * OPTIONAL }
         * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
        final ESSCertID essCertID = new ESSCertID(
                MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded()), isuerSerial);

        /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
         * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
         * OPTIONAL }
         * CertPolicyId ::= OBJECT IDENTIFIER
         * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
         * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

        final SigningCertificate scv;
        if (policy.getPolicyIdentifier() != null) {

            /** SigningCertificateV2 ::= SEQUENCE { certs SEQUENCE OF
             * ESSCertIDv2, policies SEQUENCE OF PolicyInformation OPTIONAL
             * } */
            /*
             * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
             * CASTLE NO TIENE DICHO CONSTRUCTOR.
             */
            final ASN1EncodableVector v = new ASN1EncodableVector();
            v.add(new DERSequence(essCertID));
            v.add(new DERSequence(getPolicyInformation(policy)));
            scv = SigningCertificate.getInstance(new DERSequence(v)); // con politica
        } else {
            scv = new SigningCertificate(essCertID); // Sin politica
        }

        /** id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
         * member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16)
         * id-aa(2) 12 } */
        // Secuencia con singningCertificate
        contexExpecific.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(scv)));
    }

    // INICIO SIGPOLICYID ATTRIBUTE

    if (policy.getPolicyIdentifier() != null) {
        /*
         * SigPolicyId ::= OBJECT IDENTIFIER Politica de firma.
         */
        final ASN1ObjectIdentifier doiSigPolicyId = new ASN1ObjectIdentifier(
                policy.getPolicyIdentifier().toLowerCase().replace("urn:oid:", "")); //$NON-NLS-1$ //$NON-NLS-2$

        /*
         *   OtherHashAlgAndValue ::= SEQUENCE {
         *     hashAlgorithm    AlgorithmIdentifier,
         *     hashValue        OCTET STRING }
         *
         */

        // Algoritmo para el hash
        final AlgorithmIdentifier hashid;
        // si tenemos algoritmo de calculo de hash, lo ponemos
        if (policy.getPolicyIdentifierHashAlgorithm() != null) {
            hashid = SigUtils.makeAlgId(AOAlgorithmID
                    .getOID(AOSignConstants.getDigestAlgorithmName(policy.getPolicyIdentifierHashAlgorithm())));
        }
        // si no tenemos, ponemos el algoritmo de firma.
        else {
            hashid = digestAlgorithmOID;
        }
        // hash del documento, descifrado en b64
        final byte[] hashed;
        if (policy.getPolicyIdentifierHash() != null) {
            hashed = Base64.decode(policy.getPolicyIdentifierHash());
        } else {
            hashed = new byte[] { 0 };
        }

        final DigestInfo otherHashAlgAndValue = new DigestInfo(hashid, hashed);

        /*
         *   SigPolicyQualifierInfo ::= SEQUENCE {
         *       SigPolicyQualifierId  SigPolicyQualifierId,
         *       SigQualifier          ANY DEFINED BY policyQualifierId }
         */
        SigPolicyQualifierInfo spqInfo = null;
        if (policy.getPolicyQualifier() != null) {
            spqInfo = new SigPolicyQualifierInfo(policy.getPolicyQualifier().toString());
        }

        /*
         * SignaturePolicyId ::= SEQUENCE {
         *  sigPolicyId           SigPolicyId,
         *  sigPolicyHash         SigPolicyHash,
         *  sigPolicyQualifiers   SEQUENCE SIZE (1..MAX) OF
         *                          SigPolicyQualifierInfo OPTIONAL}
         *
         */
        final ASN1EncodableVector v = new ASN1EncodableVector();
        // sigPolicyId
        v.add(doiSigPolicyId);
        // sigPolicyHash
        v.add(otherHashAlgAndValue.toASN1Primitive()); // como sequence
        // sigPolicyQualifiers
        if (spqInfo != null) {
            v.add(spqInfo.toASN1Primitive());
        }

        final DERSequence ds = new DERSequence(v);

        // Secuencia con singningCertificate
        contexExpecific.add(
                new Attribute(PKCSObjectIdentifiers.id_aa_ets_sigPolicyId, new DERSet(ds.toASN1Primitive())));
        // FIN SIGPOLICYID ATTRIBUTE
    }

    return contexExpecific;
}

From source file:es.gob.afirma.signers.cades.CAdESUtils.java

License:Open Source License

/** Genera una estructura <i>SigningCertificateV2</i> seg&uacute;n RFC 5035:
 *
 * <pre>/* ww w  . j a v  a2  s .  c  o  m*/
 * id-aa-signingCertificate OBJECT IDENTIFIER ::= { iso(1)
 *      member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9)
 *      smime(16) id-aa(2) 12
 * }
 *
 * SigningCertificate ::=  SEQUENCE {
 *      certs        SEQUENCE OF ESSCertID,
 *      policies     SEQUENCE OF PolicyInformation OPTIONAL
 * }
 * </pre>
 *
 * @param cert Certificado del firmante
 * @param digestAlgorithmName Nombre del algoritmo de huella digital a usar
 * @param policy Pol&iacute;tica de firma
 * @return Estructura <i>SigningCertificate</i> seg&uacute;n RFC 5035
 * @throws CertificateEncodingException Si el certificado proporcionado no es v&aacute;lido
 * @throws NoSuchAlgorithmException Si no se soporta el algoritmo de huella indicado */
private static Attribute getSigningCertificateV1(final X509Certificate cert, final String digestAlgorithmName,
        final AdESPolicy policy) throws CertificateEncodingException, NoSuchAlgorithmException {

    // INICIO SINGNING CERTIFICATE

    /** IssuerSerial ::= SEQUENCE { issuer GeneralNames, serialNumber
     * CertificateSerialNumber } */

    final GeneralName gn = new GeneralName(X500Name.getInstance(cert.getIssuerX500Principal().getEncoded()));
    final GeneralNames gns = new GeneralNames(gn);

    final IssuerSerial isuerSerial = new IssuerSerial(gns, cert.getSerialNumber());

    /** ESSCertID ::= SEQUENCE { certHash Hash, issuerSerial IssuerSerial
     * OPTIONAL }
     * Hash ::= OCTET STRING -- SHA1 hash of entire certificate */
    final byte[] certHash = MessageDigest.getInstance(digestAlgorithmName).digest(cert.getEncoded());
    final ESSCertID essCertID = new ESSCertID(certHash, isuerSerial);

    /** PolicyInformation ::= SEQUENCE { policyIdentifier CertPolicyId,
     * policyQualifiers SEQUENCE SIZE (1..MAX) OF PolicyQualifierInfo
     * OPTIONAL }
     * CertPolicyId ::= OBJECT IDENTIFIER
     * PolicyQualifierInfo ::= SEQUENCE { policyQualifierId
     * PolicyQualifierId, qualifier ANY DEFINED BY policyQualifierId } */

    final SigningCertificate scv;
    if (policy != null && policy.getPolicyIdentifier() != null) {

        /** SigningCertificateV2 ::= SEQUENCE {
         *    certs SEQUENCE OF ESSCertIDv2,
         *    policies SEQUENCE OF PolicyInformation OPTIONAL
         *  } */

        /*
         * HAY QUE HACER UN SEQUENCE, YA QUE EL CONSTRUCTOR DE BOUNCY
         * CASTLE NO TIENE DICHO CONSTRUCTOR.
         */
        final ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(new DERSequence(essCertID));
        v.add(new DERSequence(getPolicyInformation(policy)));
        scv = SigningCertificate.getInstance(new DERSequence(v)); // con politica
    } else {
        scv = new SigningCertificate(essCertID); // Sin politica
    }

    /** id-aa-signingCertificate OBJECT IDENTIFIER ::= {
     *    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) pkcs9(9) smime(16) id-aa(2) 12
     *  } */

    return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(scv));
}

From source file:es.gob.afirma.signers.cades.CAdESValidator.java

License:Open Source License

/** Verifica que los <code>SignerInfos</code> tengan el par&aacute;metro
 * que identifica que los datos son de tipo CAdES.
 * @param si <code>SignerInfo</code> para la verificaci&oacute;n del par&aacute;metro
 *        adecuado./*from   w  w  w .  ja v  a 2s.  com*/
 * @return si contiene el par&aacute;metro. */
private static boolean verifySignerInfo(final SignerInfo si) {
    boolean isSignerValid = false;
    final ASN1Set attrib = si.getAuthenticatedAttributes();
    final Enumeration<?> e = attrib.getObjects();
    Attribute atribute;
    while (e.hasMoreElements()) {
        final ASN1Sequence seq = (ASN1Sequence) e.nextElement();
        atribute = new Attribute((ASN1ObjectIdentifier) seq.getObjectAt(0), (ASN1Set) seq.getObjectAt(1));

        // Si tiene la politica es CADES.
        if (atribute.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signingCertificate)
                || atribute.getAttrType().equals(PKCSObjectIdentifiers.id_aa_signingCertificateV2)) {
            isSignerValid = true;
        }
    }
    return isSignerValid;
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESLevelBaselineB.java

License:Open Source License

private void addSigningCertificateAttribute(final SignatureParameters parameters,
        final ASN1EncodableVector signedAttributes) throws DSSException {

    final DigestAlgorithm digestAlgorithm = parameters.getDigestAlgorithm();
    final X509Certificate signingCertificate = parameters.getSigningCertificate();
    final byte[] encoded = DSSUtils.getEncoded(signingCertificate);
    final byte[] certHash = DSSUtils.digest(digestAlgorithm, encoded);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Adding Certificate Hash {} with algorithm {}", DSSUtils.encodeHexString(certHash),
                digestAlgorithm.getName());
    }//from w  ww . j a  v a2  s.c  om
    final IssuerSerial issuerSerial = DSSUtils.getIssuerSerial(signingCertificate);
    if (digestAlgorithm == DigestAlgorithm.SHA1) {

        final ESSCertID essCertId = new ESSCertID(certHash, issuerSerial);
        final SigningCertificate cadesSigningCertificate = new SigningCertificate(essCertId);
        final DERSet attrValues = new DERSet(cadesSigningCertificate);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, attrValues);
        signedAttributes.add(attribute);
    } else {

        final ESSCertIDv2 essCertIDv2 = new ESSCertIDv2(digestAlgorithm.getAlgorithmIdentifier(), certHash,
                issuerSerial);
        final ESSCertIDv2[] essCertIDv2Array = new ESSCertIDv2[] { essCertIDv2 };
        final SigningCertificateV2 cadesSigningCertificateV2 = new SigningCertificateV2(essCertIDv2Array);
        final DERSet attrValues = new DERSet(cadesSigningCertificateV2);
        final Attribute attribute = new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, attrValues);
        signedAttributes.add(attribute);
    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESProfileBES.java

License:Open Source License

private Attribute makeSigningCertificateAttribute(SignatureParameters parameters) {
    try {/*  ww  w. j  a  v  a  2  s  . com*/
        MessageDigest dig = MessageDigest.getInstance(parameters.getDigestAlgorithm().getName(),
                new BouncyCastleProvider());
        byte[] certHash = dig.digest(parameters.getSigningCertificate().getEncoded());

        if (parameters.getDigestAlgorithm() == DigestAlgorithm.SHA1) {
            SigningCertificate sc = new SigningCertificate(new ESSCertID(certHash));

            return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate, new DERSet(sc));

        } else {
            ESSCertIDv2 essCert = new ESSCertIDv2(
                    new AlgorithmIdentifier(parameters.getDigestAlgorithm().getOid()), certHash);
            SigningCertificateV2 scv2 = new SigningCertificateV2(new ESSCertIDv2[] { essCert });

            return new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(scv2));
        }
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (CertificateException e) {
        throw new RuntimeException(e);
    }

}

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

License:Open Source License

/**
 * ETSI TS 101 733 V2.2.1 (2013-04)<p/>
 * 5.6.3 Signature Verification Process<p/>
 * TODO (Bob 28.05.2014) The position of the signing certificate must be clarified
 * ...the public key from the first certificate identified in the sequence of certificate identifiers from SigningCertificate shall be the key used to verify the digital
 * signature./*from w ww. ja  v a  2  s. c o m*/
 *
 * @return
 */
@Override
public CandidatesForSigningCertificate getCandidatesForSigningCertificate() {

    if (candidatesForSigningCertificate != null) {

        return candidatesForSigningCertificate;
    }
    LOG.debug("--> Searching the signing certificate...");
    candidatesForSigningCertificate = new CandidatesForSigningCertificate();

    final Collection<CertificateToken> keyInfoCertificates = getCertificateSource().getKeyInfoCertificates();
    final SignerId sid = signerInformation.getSID();
    for (final CertificateToken certificateToken : keyInfoCertificates) {

        final SigningCertificateValidity signingCertificateValidity = new SigningCertificateValidity(
                certificateToken);
        candidatesForSigningCertificate.add(signingCertificateValidity);

        final X509CertificateHolder x509CertificateHolder = DSSUtils.getX509CertificateHolder(certificateToken);
        final boolean match = sid.match(x509CertificateHolder);
        if (match) {

            this.signingCertificateValidity = signingCertificateValidity;
            break;
        }
    }
    if (signingCertificateValidity == null) {

        LOG.debug("--> Signing certificate not found: " + sid);
        return candidatesForSigningCertificate;
    }

    final IssuerSerial signingTokenIssuerSerial = DSSUtils
            .getIssuerSerial(signingCertificateValidity.getCertificateToken());
    final BigInteger signingTokenSerialNumber = signingTokenIssuerSerial.getSerial().getValue();
    final GeneralNames signingTokenIssuerName = signingTokenIssuerSerial.getIssuer();

    final AttributeTable signedAttributes = getSignedAttributes(signerInformation);
    final Attribute signingCertificateAttributeV1 = signedAttributes
            .get(PKCSObjectIdentifiers.id_aa_signingCertificate);
    if (signingCertificateAttributeV1 != null) {

        signingCertificateValidity.setAttributePresent(true);
        verifySigningCertificateV1(signingTokenSerialNumber, signingTokenIssuerName,
                signingCertificateAttributeV1);
        return candidatesForSigningCertificate;
    }
    final Attribute signingCertificateAttributeV2 = signedAttributes
            .get(PKCSObjectIdentifiers.id_aa_signingCertificateV2);
    if (signingCertificateAttributeV2 != null) {

        signingCertificateValidity.setAttributePresent(true);
        verifySigningCertificateV2(signingTokenSerialNumber, signingTokenIssuerName,
                signingCertificateAttributeV2);
        return candidatesForSigningCertificate;
    }
    LOG.debug("--> There is no signed reference to the signing certificate: "
            + signingCertificateValidity.getCertificateToken().getAbbreviation());
    return candidatesForSigningCertificate;
}

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

License:Open Source License

public boolean isDataForSignatureLevelPresent(final SignatureLevel signatureLevel) {

    /**/* w  w w.  j a  v  a2  s .co m*/
     * This list contains the detail information collected during the check. It is reset for each call.
     */
    info = new ArrayList<String>();

    final AttributeTable unsignedAttributes = getUnsignedAttributes(signerInformation);
    final AttributeTable signedAttributes = getSignedAttributes(signerInformation);
    boolean dataForProfilePresent = true;
    switch (signatureLevel) {
    case CAdES_BASELINE_LTA:
        dataForProfilePresent = unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV3) != null;
        // break omitted purposely
    case CAdES_101733_A:
        if (signatureLevel != SignatureLevel.CAdES_BASELINE_LTA) {
            dataForProfilePresent &= unsignedAttributes.get(OID.id_aa_ets_archiveTimestampV2) != null;
        }
        // break omitted purposely
    case CAdES_BASELINE_LT:
        final Store certificateStore = cmsSignedData.getCertificates();
        final Store crlStore = cmsSignedData.getCRLs();
        final Store ocspStore = cmsSignedData.getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);
        final Store ocspBasicStore = cmsSignedData
                .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
        final int certificateStoreSize = certificateStore.getMatches(null).size();
        final int crlStoreSize = crlStore.getMatches(null).size();
        info.add("CRL founds: " + crlStoreSize);
        final int ocspStoreSize = ocspStore.getMatches(null).size();
        info.add("OCSP founds: " + ocspStoreSize);
        final int basicOcspStoreSize = ocspBasicStore.getMatches(null).size();
        info.add("BasicOCSP founds: " + basicOcspStoreSize);
        final int ltInfoSize = crlStoreSize + ocspStoreSize + basicOcspStoreSize;
        dataForProfilePresent &= (ltInfoSize > 0);
        // break omitted purposely
    case CAdES_101733_X:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= (unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certCRLTimestamp) != null
                    || unsignedAttributes.get(PKCSObjectIdentifiers.id_aa_ets_escTimeStamp) != null);
        }
        // break omitted purposely
    case CAdES_101733_C:
        if (!signatureLevel.toString().contains("BASELINE")) {
            dataForProfilePresent &= unsignedAttributes
                    .get(PKCSObjectIdentifiers.id_aa_ets_certificateRefs) != null;
            dataForProfilePresent &= isDataForSignatureLevelPresent(SignatureLevel.CAdES_BASELINE_T);
        }
        // break omitted purposely
    case CAdES_BASELINE_T:
        dataForProfilePresent &= unsignedAttributes
                .get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken) != null;
        // break omitted purposely
    case CAdES_BASELINE_B:
        dataForProfilePresent &= ((signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificate) != null)
                || (signedAttributes.get(PKCSObjectIdentifiers.id_aa_signingCertificateV2) != null));
        break; // break placed purposely
    case CMS:
        dataForProfilePresent = true;
        break;
    default:
        throw new IllegalArgumentException("Unknown level " + signatureLevel);
    }
    return dataForProfilePresent;
}

From source file:org.signserver.module.tsa.MSAuthCodeTimeStampSigner.java

License:Open Source License

/**
 * The main method performing the actual timestamp operation.
 * Expects the signRequest to be a GenericSignRequest contining a
 * TimeStampRequest//from  w  w w  . j  ava2  s.co m
 *
 * @param signRequest
 * @param requestContext
 * @return the sign response
 * @see org.signserver.server.IProcessable#processData(org.signserver.common.ProcessRequest, org.signserver.common.RequestContext)
 */
public ProcessResponse processData(final ProcessRequest signRequest, final RequestContext requestContext)
        throws IllegalRequestException, CryptoTokenOfflineException, SignServerException {

    // Log values
    final LogMap logMap = LogMap.getInstance(requestContext);

    try {
        final ISignRequest sReq = (ISignRequest) signRequest;
        final byte[] requestbytes = (byte[]) sReq.getRequestData();

        if (requestbytes == null || requestbytes.length == 0) {
            LOG.error("Request must contain data");
            throw new IllegalRequestException("Request must contain data");
        }

        // Check that the request contains a valid TimeStampRequest object.
        if (!(signRequest instanceof GenericSignRequest)) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request wasn't an expected GenericSignRequest. ");
            LOG.error("Received request wasn't an expected GenericSignRequest");
            throw exception;
        }

        if (!((sReq.getRequestData() instanceof TimeStampRequest)
                || (sReq.getRequestData() instanceof byte[]))) {
            final IllegalRequestException exception = new IllegalRequestException(
                    "Recieved request data wasn't an expected TimeStampRequest. ");
            LOG.error("Received request data wasn't an expected TimeStampRequest");
            throw exception;
        }

        if (!validChain) {
            LOG.error("Certificate chain not correctly configured");
            throw new CryptoTokenOfflineException("Certificate chain not correctly configured");
        }

        ASN1Primitive asn1obj = ASN1Primitive.fromByteArray(Base64.decode(requestbytes));
        ASN1Sequence asn1seq = ASN1Sequence.getInstance(asn1obj);

        if (asn1seq.size() != 2) {
            LOG.error("Wrong structure, should be an ASN1Sequence with 2 elements");
            throw new IllegalRequestException("Wrong structure, should be an ASN1Sequence with 2 elements");
        }

        ASN1ObjectIdentifier oid = ASN1ObjectIdentifier.getInstance(asn1seq.getObjectAt(0));
        ASN1Sequence asn1seq1 = ASN1Sequence.getInstance(asn1seq.getObjectAt(1));

        final ContentInfo ci = new ContentInfo(asn1seq1);

        if (!oid.getId().equals(msOID)) {
            LOG.error("Invalid OID in request: " + oid.getId());
            throw new IllegalRequestException("Invalid OID in request: " + oid.getId());
        }

        if (asn1seq1.size() != 2) {
            LOG.error(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
            throw new IllegalRequestException(
                    "Wrong structure, should be an ASN1Sequence with 2 elements as the value of element 0 in the outer ASN1Sequence");
        }

        oid = ASN1ObjectIdentifier.getInstance(asn1seq1.getObjectAt(0));

        if (!oid.getId().equals(dataOID)) {
            throw new IllegalRequestException("Wrong contentType OID: " + oid.getId());
        }

        ASN1TaggedObject tag = ASN1TaggedObject.getInstance(asn1seq1.getObjectAt(1));

        if (tag.getTagNo() != 0) {
            throw new IllegalRequestException("Wrong tag no (should be 0): " + tag.getTagNo());
        }

        ASN1OctetString octets = ASN1OctetString.getInstance(tag.getObject());
        byte[] content = octets.getOctets();

        final ITimeSource timeSrc;
        final Date date;
        byte[] der;
        ICryptoInstance crypto = null;
        try {
            crypto = acquireCryptoInstance(ICryptoToken.PURPOSE_SIGN, signRequest, requestContext);

            // get signing cert certificate chain and private key
            List<Certificate> certList = this.getSigningCertificateChain(crypto);
            if (certList == null) {
                throw new SignServerException("Null certificate chain. This signer needs a certificate.");
            }

            Certificate[] certs = (Certificate[]) certList.toArray(new Certificate[certList.size()]);

            // Sign
            X509Certificate x509cert = (X509Certificate) certs[0];

            timeSrc = getTimeSource();
            if (LOG.isDebugEnabled()) {
                LOG.debug("TimeSource: " + timeSrc.getClass().getName());
            }
            date = timeSrc.getGenTime();

            if (date == null) {
                throw new ServiceUnavailableException("Time source is not available");
            }

            ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
            signedAttributes.add(new Attribute(CMSAttributes.signingTime, new DERSet(new Time(date))));

            if (includeSigningCertificateAttribute) {
                try {
                    final DERInteger serial = new DERInteger(x509cert.getSerialNumber());
                    final X509CertificateHolder certHolder = new X509CertificateHolder(x509cert.getEncoded());
                    final X500Name issuer = certHolder.getIssuer();
                    final GeneralName name = new GeneralName(issuer);
                    final GeneralNames names = new GeneralNames(name);
                    final IssuerSerial is = new IssuerSerial(names, ASN1Integer.getInstance(serial));

                    final ESSCertID essCertid = new ESSCertID(
                            MessageDigest.getInstance("SHA-1").digest(x509cert.getEncoded()), is);
                    signedAttributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificate,
                            new DERSet(new SigningCertificate(essCertid))));
                } catch (NoSuchAlgorithmException e) {
                    LOG.error("Can't find SHA-1 implementation: " + e.getMessage());
                    throw new SignServerException("Can't find SHA-1 implementation", e);
                }
            }

            AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
            DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                    signedAttributesTable);

            final String provider = cryptoToken.getProvider(ICryptoToken.PROVIDERUSAGE_SIGN);

            SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(
                    new JcaDigestCalculatorProviderBuilder().setProvider("BC").build());
            signerInfoBuilder.setSignedAttributeGenerator(signedAttributeGenerator);

            JcaContentSignerBuilder contentSigner = new JcaContentSignerBuilder(signatureAlgo);
            contentSigner.setProvider(provider);

            final SignerInfoGenerator sig = signerInfoBuilder.build(contentSigner.build(crypto.getPrivateKey()),
                    new X509CertificateHolder(x509cert.getEncoded()));

            JcaCertStore cs = new JcaCertStore(certList);

            CMSTypedData cmspba = new CMSProcessableByteArray(content);
            CMSSignedData cmssd = MSAuthCodeCMSUtils.generate(cmspba, true, Arrays.asList(sig),
                    MSAuthCodeCMSUtils.getCertificatesFromStore(cs), Collections.emptyList(), ci);

            der = ASN1Primitive.fromByteArray(cmssd.getEncoded()).getEncoded();
        } finally {
            releaseCryptoInstance(crypto, requestContext);
        }

        // Log values
        logMap.put(ITimeStampLogger.LOG_TSA_TIME, String.valueOf(date.getTime()));
        logMap.put(ITimeStampLogger.LOG_TSA_TIMESOURCE, timeSrc.getClass().getSimpleName());

        final String archiveId = createArchiveId(requestbytes,
                (String) requestContext.get(RequestContext.TRANSACTION_ID));

        final GenericSignResponse signResponse;
        byte[] signedbytes = Base64.encode(der, false);

        logMap.put(ITimeStampLogger.LOG_TSA_TIMESTAMPRESPONSE_ENCODED, new String(signedbytes));

        final Collection<? extends Archivable> archivables = Arrays.asList(
                new DefaultArchivable(Archivable.TYPE_REQUEST, REQUEST_CONTENT_TYPE, requestbytes, archiveId),
                new DefaultArchivable(Archivable.TYPE_RESPONSE, RESPONSE_CONTENT_TYPE, signedbytes, archiveId));

        if (signRequest instanceof GenericServletRequest) {
            signResponse = new GenericServletResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables,
                    RESPONSE_CONTENT_TYPE);
        } else {
            signResponse = new GenericSignResponse(sReq.getRequestID(), signedbytes,
                    getSigningCertificate(signRequest, requestContext), archiveId, archivables);
        }

        // The client can be charged for the request
        requestContext.setRequestFulfilledByWorker(true);

        return signResponse;

    } catch (IOException e) {
        final IllegalRequestException exception = new IllegalRequestException("IOException: " + e.getMessage(),
                e);
        LOG.error("IOException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CMSException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CMSException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (OperatorCreationException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("OperatorCreationException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (CertificateEncodingException e) {
        final SignServerException exception = new SignServerException(e.getMessage(), e);
        LOG.error("CertificateEncodingException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    } catch (ArrayIndexOutOfBoundsException e) {
        // the BC base64 decoder doesn't check the the base64 input length...
        final IllegalRequestException exception = new IllegalRequestException(
                "ArrayIndexOutOfBoundsException: " + e.getMessage(), e);
        LOG.error("ArrayIndexOutOfBoundsException: ", e);
        logMap.put(ITimeStampLogger.LOG_TSA_EXCEPTION, exception.getMessage());
        throw exception;
    }
}