Example usage for java.security.cert X509Certificate getEncoded

List of usage examples for java.security.cert X509Certificate getEncoded

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getEncoded.

Prototype

public abstract byte[] getEncoded() throws CertificateEncodingException;

Source Link

Document

Returns the encoded form of this certificate.

Usage

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");
    for (X509Certificate xCert : signingCertificateChain) {
        LOG.debug("Cert chain: " + xCert.getSubjectX500Principal());
    }//ww w.j  a va 2s  .c o  m

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.dss.spi.utils.XAdESValidation.java

public SignatureInfo validate(Document document, XMLSignature xmlSignature, Element signatureElement,
        X509Certificate signingCertificate) throws XAdESValidationException {

    try {/* w  w  w  .  j av a  2s .c  o  m*/
        /*
         * Get signing time from XAdES-BES extension.
         */
        Element nsElement = getNsElement(document);

        Element qualifyingPropertiesElement = XAdESUtils.findQualifyingPropertiesElement(nsElement,
                xmlSignature, signatureElement);
        if (null == qualifyingPropertiesElement) {
            throw new XAdESValidationException("no matching xades:QualifyingProperties present");
        }
        QualifyingPropertiesType qualifyingProperties = XAdESUtils.unmarshall(qualifyingPropertiesElement,
                QualifyingPropertiesType.class);
        if (false == qualifyingProperties.getTarget().equals("#" + xmlSignature.getId())) {
            throw new XAdESValidationException("xades:QualifyingProperties/@Target incorrect");
        }

        SignedPropertiesType signedProperties = qualifyingProperties.getSignedProperties();
        SignedSignaturePropertiesType signedSignatureProperties = signedProperties
                .getSignedSignatureProperties();
        XMLGregorianCalendar signingTimeXMLGregorianCalendar = signedSignatureProperties.getSigningTime();
        DateTime signingTime = new DateTime(signingTimeXMLGregorianCalendar.toGregorianCalendar().getTime());
        LOG.debug("XAdES signing time: " + signingTime);

        /*
         * Check the XAdES signing certificate
         */
        XAdESUtils.checkSigningCertificate(signingCertificate, signedSignatureProperties);

        /*
         * Get XAdES ClaimedRole.
         */
        String role = null;
        SignerRoleType signerRole = signedSignatureProperties.getSignerRole();
        if (null != signerRole) {
            ClaimedRolesListType claimedRolesList = signerRole.getClaimedRoles();
            if (null != claimedRolesList) {
                List<AnyType> claimedRoles = claimedRolesList.getClaimedRole();
                if (!claimedRoles.isEmpty()) {
                    AnyType claimedRole = claimedRoles.get(0);
                    List<Object> claimedRoleContent = claimedRole.getContent();
                    for (Object claimedRoleContentItem : claimedRoleContent) {
                        if (claimedRoleContentItem instanceof String) {
                            role = (String) claimedRoleContentItem;
                            LOG.debug("XAdES claimed role: " + role);
                            break;
                        }
                    }
                }
            }
        }

        // XAdES-T

        // validate first SignatureTimeStamp
        Element signatureTimeStampElement = XAdESUtils
                .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SignatureTimeStamp");
        if (null == signatureTimeStampElement) {
            throw new XAdESValidationException("no xades:SignatureTimeStamp present");
        }
        XAdESTimeStampType signatureTimeStamp = XAdESUtils.unmarshall(signatureTimeStampElement,
                XAdESTimeStampType.class);
        List<TimeStampToken> signatureTimeStampTokens = XAdESSignatureTimeStampValidation
                .verify(signatureTimeStamp, signatureElement);

        // XAdES-X

        // validate first SigAndRefsTimeStamp
        Element sigAndRefsTimeStampElement = XAdESUtils
                .findUnsignedSignaturePropertyElement(qualifyingPropertiesElement, "SigAndRefsTimeStamp");
        if (null == sigAndRefsTimeStampElement) {
            LOG.error("No SigAndRefsTimeStamp present");
            throw new XAdESValidationException("no xades:SigAndRefsTimeStamp present");
        }
        XAdESTimeStampType sigAndRefsTimeStamp = XAdESUtils.unmarshall(sigAndRefsTimeStampElement,
                XAdESTimeStampType.class);
        List<TimeStampToken> sigAndRefsTimeStampTokens = XAdESSigAndRefsTimeStampValidation
                .verify(sigAndRefsTimeStamp, signatureElement);

        // timestamp tokens trust validation
        LOG.debug("validate SignatureTimeStamp's trust...");
        ValidationDataType signatureTimeStampValidationData = XAdESUtils.findNextSibling(
                signatureTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData",
                ValidationDataType.class);
        if (null != signatureTimeStampValidationData) {
            LOG.debug("xadesv141:TimeStampValidationData present for xades:SignatureTimeStamp");
            RevocationValuesType revocationValues = signatureTimeStampValidationData.getRevocationValues();
            List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
            List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);
            for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
                this.documentContext.validate(signatureTimeStampToken, ocspResponses, crls);
            }
        } else {
            for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
                this.documentContext.validate(signatureTimeStampToken);
            }
        }

        LOG.debug("validate SigAndRefsTimeStamp's trust...");
        ValidationDataType sigAndRefsTimeStampValidationData = XAdESUtils.findNextSibling(
                sigAndRefsTimeStampElement, XAdESUtils.XADES_141_NS_URI, "TimeStampValidationData",
                ValidationDataType.class);
        if (null != sigAndRefsTimeStampValidationData) {
            LOG.debug("xadesv141:TimeStampValidationData present for xades:SigAndRefsTimeStamp");
            RevocationValuesType revocationValues = sigAndRefsTimeStampValidationData.getRevocationValues();
            List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
            List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);
            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                this.documentContext.validate(sigAndRefsTimeStampToken, ocspResponses, crls);
            }
        } else {
            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                this.documentContext.validate(sigAndRefsTimeStampToken);
            }
        }

        // timestamp tokens time coherence verification
        long timestampMaxOffset = this.documentContext.getTimestampMaxOffset();
        LOG.debug("validate timestamp tokens time coherence...");
        for (TimeStampToken signatureTimeStampToken : signatureTimeStampTokens) {
            DateTime stsTokenGenTime = new DateTime(signatureTimeStampToken.getTimeStampInfo().getGenTime());
            try {
                XAdESUtils.checkCloseEnough(signingTime, stsTokenGenTime, timestampMaxOffset);
            } catch (XAdESValidationException e) {
                throw new XAdESValidationException("SignatureTimeStamp too far from SigningTime", e);
            }

            for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
                DateTime sigAndRefsTokenGenTime = new DateTime(
                        sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime());
                if (sigAndRefsTokenGenTime.isBefore(stsTokenGenTime)) {
                    throw new XAdESValidationException("SigAndRefsTimeStamp before SignatureTimeStamp");
                }
            }
        }

        long maxGracePeriod = this.documentContext.getMaxGracePeriod();
        for (TimeStampToken sigAndRefsTimeStampToken : sigAndRefsTimeStampTokens) {
            DateTime sigAndRefsTokenGenTime = new DateTime(
                    sigAndRefsTimeStampToken.getTimeStampInfo().getGenTime());
            try {
                XAdESUtils.checkCloseEnough(signingTime, sigAndRefsTokenGenTime,
                        maxGracePeriod * 1000 * 60 * 60);
            } catch (XAdESValidationException e) {
                throw new XAdESValidationException("SigAndRefsTimeStamp too far from SigningTime", e);
            }
        }

        // XAdES-X-L

        /*
         * Retrieve certificate chain and revocation data from XAdES-X-L
         * extension for trust validation.
         */
        RevocationValuesType revocationValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties,
                RevocationValuesType.class, "RevocationValues");
        List<X509CRL> crls = XAdESUtils.getCrls(revocationValues);
        List<OCSPResp> ocspResponses = XAdESUtils.getOCSPResponses(revocationValues);

        CertificateValuesType certificateValues = XAdESUtils.findUnsignedSignatureProperty(qualifyingProperties,
                CertificateValuesType.class, "CertificateValues");
        if (null == certificateValues) {
            throw new XAdESValidationException("no CertificateValues element found.");
        }
        List<X509Certificate> certificateChain = XAdESUtils.getCertificates(certificateValues);
        if (certificateChain.isEmpty()) {
            throw new XAdESValidationException("no cert chain in CertificateValues");
        }

        /*
         * Check certificate chain is indeed contains the signing
         * certificate.
         */
        if (!Arrays.equals(signingCertificate.getEncoded(), certificateChain.get(0).getEncoded())) {
            // throw new XAdESValidationException(
            // "XAdES certificate chain does not include actual signing certificate");
            /*
             * Not all XAdES implementations add the entire certificate
             * chain via xades:CertificateValues.
             */
            certificateChain.add(0, signingCertificate);
        }
        LOG.debug("XAdES certificate chain contains actual signing certificate");

        // XAdES-C
        CompleteCertificateRefsType completeCertificateRefs = XAdESUtils.findUnsignedSignatureProperty(
                qualifyingProperties, CompleteCertificateRefsType.class, "CompleteCertificateRefs");
        if (null == completeCertificateRefs) {
            throw new XAdESValidationException("missing CompleteCertificateRefs");
        }
        CompleteRevocationRefsType completeRevocationRefs = XAdESUtils.findUnsignedSignatureProperty(
                qualifyingProperties, CompleteRevocationRefsType.class, "CompleteRevocationRefs");
        if (null == completeRevocationRefs) {
            throw new XAdESValidationException("missing CompleteRevocationRefs");
        }
        for (OCSPResp ocspResp : ocspResponses) {
            XAdESUtils.checkReference(ocspResp, completeRevocationRefs);
        }
        for (X509CRL crl : crls) {
            XAdESUtils.checkReference(crl, completeRevocationRefs);
        }
        Iterator<X509Certificate> certIterator = certificateChain.iterator();
        certIterator.next(); // digestion of SigningCertificate already
                             // checked
        while (certIterator.hasNext()) {
            X509Certificate certificate = certIterator.next();
            XAdESUtils.checkReference(certificate, completeCertificateRefs);
        }

        /*
         * Perform trust validation via eID Trust Service
         */
        this.documentContext.validate(certificateChain, signingTime.toDate(), ocspResponses, crls);

        /*
         * Retrieve the possible eID identity signature extension data.
         */
        String firstName = null;
        String name = null;
        String middleName = null;
        SignatureInfo.Gender gender = null;
        byte[] photo = null;

        IdentityType identity = XAdESUtils.findIdentity(nsElement, xmlSignature, signatureElement);
        if (null != identity) {
            firstName = identity.getFirstName();
            name = identity.getName();
            middleName = identity.getMiddleName();
            switch (identity.getGender()) {
            case MALE:
                gender = SignatureInfo.Gender.MALE;
                break;
            case FEMALE:
                gender = SignatureInfo.Gender.FEMALE;
                break;
            }
            photo = identity.getPhoto().getValue();
        }

        /*
         * Return the result of the signature analysis.
         */
        return new SignatureInfo(signingCertificate, signingTime.toDate(), role, firstName, name, middleName,
                gender, photo);
    } catch (CertificateEncodingException e) {
        throw new XAdESValidationException(e);
    } catch (Exception e) {
        throw new XAdESValidationException(e);
    }
}