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

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

Introduction

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

Prototype

public void setIdAttributeNS(Element element, String namespaceURI, String localName) 

Source Link

Document

Registers the element's attribute specified by the namespace URI and local name to be of type ID.

Usage

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(/*from  ww w  .  j a v a 2 s  . c  om*/
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

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);/*w ww  . j  ava 2s.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;

}

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

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

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

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

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

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);/*w  ww  .  j av a 2  s  .  co m*/

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    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);

    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);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

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

    digestReferences(signContext, references);

    return signature;

}

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   www.jav a2s  .  c  om
        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:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException, NoSuchProviderException, SOAPException {
    if (null == this.privateKey) {
        return;//from   w  w w. j  a v a  2  s .  co  m
    }
    DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement);
    domSignContext.setDefaultNamespacePrefix("ds");
    domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id");
    domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id");
    LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS")));
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

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

    List<String> tsPrefixes = new LinkedList<String>();
    tsPrefixes.add("wsse");
    tsPrefixes.add("S");
    ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes);
    Reference tsReference = xmlSignatureFactory.newReference("#TS",
            xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
            Collections.singletonList(
                    xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)),
            null, null);
    references.add(tsReference);

    if (this.signBody) {
        List<String> bodyPrefixes = new LinkedList<String>();
        ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes);
        Reference bodyReference = xmlSignatureFactory.newReference("#Body",
                xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                Collections.singletonList(
                        xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)),
                null, null);
        references.add(bodyReference);
    }

    if (this.signBinarySecurityToken) {
        Reference bstReference = xmlSignatureFactory
                .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                        Collections.singletonList(xmlSignatureFactory
                                .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)),
                        null, null);
        references.add(bstReference);
    }

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references);

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE,
            "wsse:SecurityTokenReference");
    Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference");
    referenceElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
    referenceElement.setAttribute("URI", "#X509");
    securityTokenReferenceElement.appendChild(referenceElement);
    KeyInfo keyInfo = keyInfoFactory
            .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement)));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo, null, "SIG", null);
    xmlSignature.sign(domSignContext);
}