Example usage for javax.xml.crypto.dsig.dom DOMSignContext setURIDereferencer

List of usage examples for javax.xml.crypto.dsig.dom DOMSignContext setURIDereferencer

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig.dom DOMSignContext setURIDereferencer.

Prototype

public void setURIDereferencer(URIDereferencer dereferencer) 

Source Link

Usage

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
* Method used to create an enveloped digital signature for an element of a TAXII document.
*
* @param element the element to be signed
* @param keyEntry the PrivateKeyEntry/*from  ww w . j a v  a2 s . com*/
* @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element
* @return the status of the operation
*
* Usage Example:
*   String pks = config.getProperty("pathToPublisherKeyStore");
*    String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword"));
*    String keyName = config.getProperty("publisherKeyName");
*    String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword"));
*   PrivateKeyEntry keyEntry =  FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW);
*   List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1);
*/
private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) {
    element.normalize();
    boolean status = false;

    //Create XML Signature Factory
    XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM");
    PublicKey publicKey = ClientUtil.getPublicKey(keyEntry);
    PrivateKey privateKey = keyEntry.getPrivateKey();
    DOMSignContext dsc = new DOMSignContext(privateKey, element);
    dsc.setDefaultNamespacePrefix("ds");
    dsc.setURIDereferencer(new MyURIDereferencer(element));
    SignedInfo si = null;
    DigestMethod dm = null;
    SignatureMethod sm = null;
    KeyInfo ki = null;
    X509Data xd;
    List<Serializable> x509Content = new ArrayList<>();
    try {
        String algorithm = publicKey.getAlgorithm();
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        String algorithmName = cert.getSigAlgName();
        if (algorithm.toUpperCase().contains("RSA")) {
            if (algorithmName.toUpperCase().contains("SHA1")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null);
                sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            } else if (algorithmName.toUpperCase().contains("SHA2")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null);
                sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null);
            } else {
                logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
            }
            CanonicalizationMethod cm;
            if (cbIndex != -1) {
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex
                        + "]/*[local-name()='Content'][1]/*)";
                List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            } else {
                List<Transform> transforms = new ArrayList<>(2);
                transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
                transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                        (TransformParameterSpec) null));
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(/*)";
                List<Reference> references = Collections
                        .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            }
            KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory();
            xd = kif.newX509Data(x509Content);
            ki = kif.newKeyInfo(Collections.singletonList(xd));
        } else {
            logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document.");
    } catch (InvalidAlgorithmParameterException ex) {
        logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document.");
    }

    // Create a new XML Signature
    XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki);
    try {
        // Sign the document
        signature.sign(dsc);
        status = true;
    } catch (MarshalException ex) {
        logger.error("MarshalException when attempting to digitally sign a document.");
    } catch (XMLSignatureException ex) {
        logger.error("XMLSignature Exception when attempting to digitally sign a document.");
    } catch (Exception e) {
        logger.error("General exception when attempting to digitally sign a document.");
    }
    return status;
}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

@Override
public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException {

    try {//w w w.  ja  v a  2  s  .  c  o  m
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        XMLStructure s = new DOMStructure(signatureElement);
        XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
        DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s);

        DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement);
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true);
        signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData));

        // TODO naramsda: check ! Don't let met publish that without further test !!
        // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // dbf.setNamespaceAware(true);
        // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument();
        // signature.marshal(xmlDoc.createElement("test"), "ds", signContext);

        for (Object o : signature.getSignedInfo().getReferences()) {
            DOMReference r = (DOMReference) o;
            InputStream data = r.getDigestInputStream();
            if (data != null) {
                IOUtils.copy(data, buffer);
            }
        }

        List<Node> timeStampNodesXadesA = new LinkedList<Node>();

        Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo");
        timeStampNodesXadesA.add(signedInfo);

        Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue");
        timeStampNodesXadesA.add(signatureValue);

        Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo");
        timeStampNodesXadesA.add(keyInfo);

        Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement);

        NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes();
        int count = 0;
        for (int i = 0; i < unsignedProperties.getLength(); i++) {
            if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element unsignedProperty = (Element) unsignedProperties.item(i);
                if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) {
                    if (count == index) {
                        LOG.info("We only need data up to ArchiveTimeStamp index " + index);
                        break;
                    }
                    count++;
                }
                timeStampNodesXadesA.add(unsignedProperty);
            }
        }

        buffer.write(getC14nValue(timeStampNodesXadesA));

        return buffer.toByteArray();
        //        } catch (ParserConfigurationException e) {
        //            throw new IOException("Error when computing the archive data", e);
    } catch (MarshalException e) {
        throw new IOException("Error when computing the archive data", e);
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING);
    }
}

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

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override/*from w  w w. ja  v a2 s.co m*/
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

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

private DOMXMLSignature createDetached(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, final Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    // Create references
    List<Reference> references = new ArrayList<Reference>();
    addReferences(documentIterator(inside), references, digestMethod, fac);
    // Create repository
    signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac));

    List<XMLObject> objects = new ArrayList<XMLObject>();

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, references, inside);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);/* www .  j  a  v a2 s.co m*/

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}