Example usage for org.bouncycastle.asn1.ocsp ResponderID toASN1Object

List of usage examples for org.bouncycastle.asn1.ocsp ResponderID toASN1Object

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.ocsp ResponderID toASN1Object.

Prototype

public ASN1Primitive toASN1Object() 

Source Link

Usage

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

License:Open Source License

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }//from ww w  . jav  a  2 s.  c  o m

    // 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:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java

License:Open Source License

/**
 * Finds notary cert by responder-id field in basic ocsp response
 * @param basResp basic ocsp response//from  w  w  w  . j av  a  2 s  . co m
 * @return notary cert or null if not found
 */
private X509Certificate findNotaryCertByResponderId(BasicOCSPResp basResp) {
    if (basResp != null) {
        ResponderID respid = basResp.getResponderId().toASN1Object();
        Object o = ((DERTaggedObject) respid.toASN1Object()).getObject();
        System.out.println("resp-id-test: " + o.toString());
        if (o instanceof ASN1Sequence) {
            X509Name name = new X509Name((ASN1Sequence) o);
            String dn = name.toString();
            String cn = SignedDoc.getCommonName(dn);
            System.out.println("Find notary for: " + dn + " -> " + cn);
            return getNotaryCert(cn, null);
        } else if (o instanceof DEROctetString) {
            DEROctetString dHash = (DEROctetString) o;
            byte[] cHash = null;
            byte[] cHash2 = null;
            byte[] cHash3 = null;
            try {
                cHash = dHash.getOctets();
                cHash2 = dHash.getDEREncoded();
                cHash3 = dHash.getEncoded();
            } catch (Exception ex) {
                m_logger.error("Error: " + ex);
            }
            System.out.println("Find notary for octects: " + Base64Util.encode(cHash) + " len: " + cHash.length
                    + " hex: " + SignedDoc.bin2hex(cHash) + " der: " + Base64Util.encode(cHash2) + " len: "
                    + cHash2.length + " enc: " + Base64Util.encode(cHash3) + " len: " + cHash3.length);
            return findNotaryCertByKeyHash(cHash);
        } else {
            return null;
        }
    } else
        return null;
}

From source file:ee.sk.digidoc.factory.BouncyCastleNotaryFactory.java

License:Open Source License

/**
* Get String represetation of ResponderID
* @param basResp/* w  w  w .ja  v a  2s .  c om*/
* @return stringified responder ID
*/
private String responderIDtoString(BasicOCSPResp basResp) {
    if (basResp != null) {
        ResponderID respid = basResp.getResponderId().toASN1Object();
        Object o = ((DERTaggedObject) respid.toASN1Object()).getObject();
        //System.out.println("resp-id-test: " + o.toString());
        if (o instanceof ASN1Sequence) {
            X509Name name = new X509Name((ASN1Sequence) o);
            return "byName: " + name.toString();
        } else if (o instanceof DEROctetString) {
            // TODO: fix ...
            return "byKey: " + o.toString();
        } else {
            return null;
        }
    } else
        return null;
}

From source file:es.uji.security.crypto.openxades.digidoc.factory.BouncyCastleNotaryFactory.java

License:Open Source License

/**
 * Get String represetation of ResponderID
 * /*www.j ava  2 s.  c  om*/
 * @param basResp
 * @return stringified responder ID
 */
private String responderIDtoString(BasicOCSPResp basResp) {
    if (basResp != null) {
        ResponderID respid = basResp.getResponseData().getResponderId().toASN1Object();
        Object o = ((DERTaggedObject) respid.toASN1Object()).getObject();

        if (o instanceof ASN1Sequence) {
            X509Name name = new X509Name((ASN1Sequence) o);
            return "byName: " + name.toString();
        } else {
            X509Certificate[] result = null;

            try {
                result = basResp.getCerts("BC");
            } catch (Exception e) {
            }

            if (result != null && result.length > 0) {
                return "byName: " + result[0].getSubjectDN().getName();
            }
        }
    }

    return null;
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileC.java

License:Open Source License

private void incorporateOCSPRefs(CompleteRevocationRefsType completeRevocationRefs, ValidationContext ctx) {
    if (!ctx.getNeededOCSPResp().isEmpty()) {
        OCSPRefsType ocspRefs = this.xadesObjectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();

        for (BasicOCSPResp basicOcspResp : ctx.getNeededOCSPResp()) {
            try {
                OCSPRefType ocspRef = this.xadesObjectFactory.createOCSPRefType();

                DigestAlgAndValueType digestAlgAndValue = getDigestAlgAndValue(
                        OCSPUtils.fromBasicToResp(basicOcspResp).getEncoded(), DigestAlgorithm.SHA1);
                LOG.info("Add a reference for OCSP produced at " + basicOcspResp.getProducedAt() + " digest "
                        + Hex.encodeHexString(digestAlgAndValue.getDigestValue()));
                ocspRef.setDigestAlgAndValue(digestAlgAndValue);

                OCSPIdentifierType ocspIdentifier = xadesObjectFactory.createOCSPIdentifierType();
                ocspRef.setOCSPIdentifier(ocspIdentifier);

                Date producedAt = basicOcspResp.getProducedAt();

                GregorianCalendar cal = (GregorianCalendar) GregorianCalendar.getInstance();
                cal.setTime(producedAt);

                ocspIdentifier.setProducedAt(this.datatypeFactory.newXMLGregorianCalendar(cal));

                ResponderIDType responderId = this.xadesObjectFactory.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());
                }//from   w  ww  .j  a va2s  . co  m

                ocspRefList.add(ocspRef);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
    }
}