Example usage for org.w3c.dom Element setIdAttribute

List of usage examples for org.w3c.dom Element setIdAttribute

Introduction

In this page you can find the example usage for org.w3c.dom Element setIdAttribute.

Prototype

public void setIdAttribute(String name, boolean isId) throws DOMException;

Source Link

Document

If the parameter isId is true, this method declares the specified attribute to be a user-determined ID attribute .

Usage

From source file:be.e_contract.mycarenet.xkms2.ProofOfPossessionSignatureSOAPHandler.java

private void prepareDocument(Document xkmsDocument) {
    Element prototypeElement = xkmsDocument.getElementById(this.prototypeKeyBindingId);
    if (null == prototypeElement) {
        LOG.warn("Prototype element not found via Id");
        prototypeElement = (Element) xkmsDocument
                .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "PrototypeKeyBinding").item(0);
        prototypeElement.setIdAttribute("Id", true);
    }/*from w w  w.j av  a  2 s. c  om*/
}

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

private Node marshallQualifyingProperties(Document document, ObjectFactory xadesObjectFactory,
        QualifyingPropertiesType qualifyingProperties) {
    Node marshallNode = document.createElement("marshall-node");
    try {//from w  ww.j a va2 s  .  c o m
        this.marshaller.marshal(xadesObjectFactory.createQualifyingProperties(qualifyingProperties),
                marshallNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
    Element qualifyingPropertiesElement = (Element) marshallNode.getFirstChild();
    Element signedPropertiesElement = (Element) qualifyingPropertiesElement
            .getElementsByTagNameNS("http://uri.etsi.org/01903/v1.3.2#", "SignedProperties").item(0);
    signedPropertiesElement.setIdAttribute("Id", true);
    return qualifyingPropertiesElement;
}

From source file:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java

private void prepareDocument(Document xkmsDocument) {
    Element prototypeElement = xkmsDocument.getElementById(this.prototypeKeyBindingId);
    if (null == prototypeElement) {
        LOG.warn("Prototype element not found via Id");
        prototypeElement = (Element) xkmsDocument
                .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "PrototypeKeyBinding").item(0);
        if (null == prototypeElement) {
            prototypeElement = (Element) xkmsDocument
                    .getElementsByTagNameNS(XKMS2ServiceFactory.XKMS2_NAMESPACE, "RevokeKeyBinding").item(0);
        }//from ww w. j  a  v a2 s . co  m
        prototypeElement.setIdAttribute("Id", true);
    }
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

/**
 * Sign DOM document//from w  w w  .j a  va 2  s . co m
 * 
 * @param documentElement
 *            document to be signed
 * @param nextSibling
 *            next sibling in document, dsig is added before this one
 * @param identity
 *            Identity to sign with
 * @throws NoSuchAlgorithmException
 *             signing algorithm not found
 * @throws InvalidAlgorithmParameterException
 *             invalid signing algo param
 * @throws MarshalException
 *             error marshalling signature
 * @throws XMLSignatureException
 *             error during signing
 */
public static void signDocument(Element documentElement, Node nextSibling, KeyStore.PrivateKeyEntry identity)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {

    // get document ID
    String documentId = documentElement.getAttribute("ID");
    LOG.debug("document ID=" + documentId);

    // fix for recent versions of Apache xmlsec.
    documentElement.setIdAttribute("ID", true);

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    XMLSignContext signContext = new DOMSignContext(identity.getPrivateKey(), documentElement, nextSibling);
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");
    javax.xml.crypto.dsig.DigestMethod digestMethod = signatureFactory
            .newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null);

    List<javax.xml.crypto.dsig.Transform> transforms = new LinkedList<javax.xml.crypto.dsig.Transform>();
    transforms.add(signatureFactory.newTransform(javax.xml.crypto.dsig.Transform.ENVELOPED,
            (TransformParameterSpec) null));
    javax.xml.crypto.dsig.Transform exclusiveTransform = signatureFactory
            .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

    Reference reference = signatureFactory.newReference("#" + documentId, digestMethod, transforms, null, null);

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(reference));

    List<Object> keyInfoContent = new LinkedList<Object>();
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();

    for (X509Certificate certificate : Saml2Util.getCertificateChain(identity)) {
        x509DataObjects.add(certificate);
    }
    javax.xml.crypto.dsig.keyinfo.X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);
    javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    xmlSignature.sign(signContext);
}

From source file:be.fedict.eid.idp.protocol.ws_federation.sts.SecurityTokenServicePortImpl.java

private void validateToken(Element tokenElement, String expectedAudience,
        IdentityProviderConfiguration identityProviderConfiguration) throws Exception {
    List<X509Certificate> certificateChain = identityProviderConfiguration.getIdentityCertificateChain();
    if (certificateChain.isEmpty()) {
        throw new SecurityException("no eID IdP service identity configured");
    }/*from   w ww  . j ava 2  s .c  o  m*/

    Element nsElement = tokenElement.getOwnerDocument().createElement("nsElement");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:ds", "http://www.w3.org/2000/09/xmldsig#");
    nsElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:saml2", "urn:oasis:names:tc:SAML:2.0:assertion");
    LOG.debug("token element: " + tokenElement.getLocalName());
    LOG.debug("token element namespace: " + tokenElement.getNamespaceURI());
    LOG.debug("token: " + toString(tokenElement));

    // fix for recent versions of Apache xmlsec.
    tokenElement.setIdAttribute("ID", true);

    Element signatureElement = (Element) XPathAPI.selectSingleNode(tokenElement, "ds:Signature", nsElement);
    if (null == signatureElement) {
        throw new SecurityException("missing XML signature");
    }

    XMLSignature xmlSignature = new XMLSignature(signatureElement, "");
    KeyInfo keyInfo = xmlSignature.getKeyInfo();
    X509Certificate actualCertificate = keyInfo.getX509Certificate();
    boolean signatureResult = xmlSignature.checkSignatureValue(actualCertificate);
    if (false == signatureResult) {
        throw new SecurityException("invalid XML signature");
    }
    LOG.debug("XML signature OK");

    X509Certificate serviceCertificate = certificateChain.get(0);
    if (false == Arrays.equals(serviceCertificate.getEncoded(), actualCertificate.getEncoded())) {
        throw new SecurityException("SAML signing certificate different from eID IdP service identity");
    }
    LOG.debug("SAML signer OK");

    String actualIssuer = XPathAPI.selectSingleNode(tokenElement, "saml2:Issuer/text()", nsElement)
            .getNodeValue();
    String serviceIssuer = identityProviderConfiguration.getDefaultIssuer();
    if (false == actualIssuer.equals(serviceIssuer)) {
        LOG.debug("actual issuer: " + actualIssuer);
        LOG.debug("service issuer: " + serviceIssuer);
        throw new SecurityException("wrong SAML issuer");
    }
    LOG.debug("SAML issuer OK");

    if (null != expectedAudience) {
        String audience = XPathAPI
                .selectSingleNode(tokenElement,
                        "saml2:Conditions/saml2:AudienceRestriction/saml2:Audience/text()", nsElement)
                .getNodeValue();
        if (false == expectedAudience.equals(audience)) {
            LOG.debug("expected audience: " + expectedAudience);
            LOG.debug("actual audience: " + audience);
            throw new SecurityException("incorrect SAML audience");
        }
        LOG.debug("SAML Audience OK");
    } else {
        LOG.warn("SAML audience restriction not checked");
    }

    String authnContextClassRef = XPathAPI
            .selectSingleNode(tokenElement,
                    "saml2:AuthnStatement/saml2:AuthnContext/saml2:AuthnContextClassRef/text()", nsElement)
            .getNodeValue();
    LOG.debug("AuthnContextClassRef: " + authnContextClassRef);
    SamlAuthenticationPolicy samlAuthenticationPolicy = SamlAuthenticationPolicy
            .getAuthenticationPolicy(authnContextClassRef);
    if (SamlAuthenticationPolicy.AUTHENTICATION != samlAuthenticationPolicy
            && SamlAuthenticationPolicy.AUTHENTICATION_WITH_IDENTIFICATION != samlAuthenticationPolicy) {
        throw new SecurityException("wrong SAML authentication policy: " + samlAuthenticationPolicy);
    }

    String notBeforeStr = XPathAPI.selectSingleNode(tokenElement, "saml2:Conditions/@NotBefore", nsElement)
            .getNodeValue();
    String notOnOrAfterStr = XPathAPI
            .selectSingleNode(tokenElement, "saml2:Conditions/@NotOnOrAfter", nsElement).getNodeValue();
    DateTimeFormatter dateTimeFormatter = ISODateTimeFormat.dateTimeParser();
    DateTime notBefore = dateTimeFormatter.parseDateTime(notBeforeStr);
    DateTime notOnOrAfter = dateTimeFormatter.parseDateTime(notOnOrAfterStr);
    DateTime now = new DateTime();
    if (now.isBefore(notBefore)) {
        throw new SecurityException("SAML assertion in future");
    }
    if (now.isAfter(notOnOrAfter)) {
        throw new SecurityException("SAML assertion expired");
    }
    LOG.debug("SAML timestamp OK");
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

@Override
public Output get(Input input) throws Exception { //NOPMD

    XmlSignatureProperties.Output result = new Output();

    if (!isAddSignedSignatureProperties() && !isAddSignedDataObjectPropeties()) {
        LOG.debug(/*w  w  w . ja  v a2  s  .  c om*/
                "XAdES signature properties are empty. Therefore no XAdES element will be added to the signature.");
        return result;
    }
    String signedPropertiesId = "_" + UUID.randomUUID().toString();
    Reference ref = input.getSignatureFactory().newReference("#" + signedPropertiesId,
            input.getSignatureFactory().newDigestMethod(input.getContentDigestAlgorithm(), null),
            Collections.emptyList(), "http://uri.etsi.org/01903#SignedProperties", null);

    Node parent = input.getParent();
    Document doc;
    if (Node.DOCUMENT_NODE == parent.getNodeType()) {
        doc = (Document) parent; // enveloping
    } else {
        doc = parent.getOwnerDocument(); // enveloped
    }

    Element qualifyingProperties = createElement("QualifyingProperties", doc, input);
    setIdAttributeFromHeader(XmlSignatureConstants.HEADER_XADES_QUALIFYING_PROPERTIES_ID, qualifyingProperties,
            input);
    String signatureId = input.getSignatureId();
    if (signatureId == null || signatureId.isEmpty()) {
        LOG.debug("No signature Id configured. Therefore a value is generated.");
        // generate one
        signatureId = "_" + UUID.randomUUID().toString();
        // and set to output
        result.setSignatureId(signatureId);
    }
    setAttribute(qualifyingProperties, "Target", "#" + signatureId);
    Element signedProperties = createElement("SignedProperties", doc, input);
    qualifyingProperties.appendChild(signedProperties);
    setAttribute(signedProperties, "Id", signedPropertiesId);
    signedProperties.setIdAttribute("Id", true);
    addSignedSignatureProperties(doc, signedProperties, input);
    String contentReferenceId = addSignedDataObjectProperties(doc, signedProperties, input);
    result.setContentReferenceId(contentReferenceId);
    DOMStructure structure = new DOMStructure(qualifyingProperties);

    XMLObject propertiesObject = input.getSignatureFactory().newXMLObject(Collections.singletonList(structure),
            null, null, null);

    result.setReferences(Collections.singletonList(ref));
    result.setObjects(Collections.singletonList(propertiesObject));

    return result;
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void setIdAttributeFromHeader(String header, Element element, Input input) {
    String value = input.getMessage().getHeader(header, String.class);
    if (value != null && !value.isEmpty()) {
        setAttribute(element, "Id", value);
        element.setIdAttribute("Id", true);
    }/*from w  w w .j a v a 2  s . c om*/
}

From source file:org.apache.camel.component.xmlsecurity.api.XAdESSignatureProperties.java

protected void addSignerRole(Document doc, Element signedSignatureProperties, Input input)
        throws XmlSignatureException, SAXException, IOException, ParserConfigurationException {
    if (!isAddSignerRole()) {
        return;//from   ww  w .ja  v  a2  s  .  c  o  m
    }
    Element signerRole = createElement("SignerRole", doc, input);
    signedSignatureProperties.appendChild(signerRole);
    List<String> claimedRoles = getSignerClaimedRoles();
    if (!claimedRoles.isEmpty()) {
        LOG.debug("Adding claimed roles");
        Element claimedRolesEl = createElement("ClaimedRoles", doc, input);
        signerRole.appendChild(claimedRolesEl);
        String errorMessage = "The XAdES confguration is invalid. The list of the claimed roles contains the invalid entry '%s'."
                + " An entry must either be a text or an XML fragment with the root element '%s' with the namespace '%s'.";
        for (String claimedRole : claimedRoles) {
            Element claimedRoleEl = createChildFromXmlFragmentOrText(doc, input, "ClaimedRole", errorMessage,
                    claimedRole);
            claimedRolesEl.appendChild(claimedRoleEl);
        }
    }
    List<XAdESEncapsulatedPKIData> certifiedRoles = getSignerCertifiedRoles();
    if (!certifiedRoles.isEmpty()) {
        LOG.debug("Adding certified roles");
        Element certifiedRolesEl = createElement("CertifiedRoles", doc, input);
        signerRole.appendChild(certifiedRolesEl);
        for (XAdESEncapsulatedPKIData certifiedRole : certifiedRoles) {
            Element certifiedRoleEl = createElement("CertifiedRole", doc, input);
            certifiedRolesEl.appendChild(certifiedRoleEl);
            certifiedRoleEl.setTextContent(certifiedRole.getBase64Conent());
            if (certifiedRole.getEncoding() != null && !certifiedRole.getEncoding().isEmpty()) {
                setAttribute(certifiedRoleEl, "Encoding", certifiedRole.getEncoding());
            }
            if (certifiedRole.getId() != null && !certifiedRole.getId().isEmpty()) {
                setAttribute(certifiedRoleEl, "Id", certifiedRole.getId());
                certifiedRoleEl.setIdAttribute("Id", true);
            }
        }
    }

}

From source file:org.apereo.portal.layout.dlm.DeleteManager.java

/**
   Attempt to apply a single delete command and return true if it succeeds
   or false otherwise. If the delete is disallowed or the target element
   no longer exists in the document the delete command fails and returns
   false.//  w  ww.j  a  v a  2 s.c  o m
*/
private static boolean applyDelete(Element delete, Document ilf) {
    String nodeID = delete.getAttribute(Constants.ATT_NAME);

    Element e = ilf.getElementById(nodeID);

    if (e == null)
        return false;

    String deleteAllowed = e.getAttribute(Constants.ATT_DELETE_ALLOWED);
    if (deleteAllowed.equals("false"))
        return false;

    Element p = (Element) e.getParentNode();
    e.setIdAttribute(Constants.ATT_ID, false);
    p.removeChild(e);
    return true;
}

From source file:org.apereo.portal.layout.dlm.DistributedLayoutManager.java

public IUserLayoutNodeDescription addNode(IUserLayoutNodeDescription node, String parentId,
        String nextSiblingId) throws PortalException {
    boolean isChannel = false;
    IUserLayoutNodeDescription parent = this.getNode(parentId);
    if (canAddNode(node, parent, nextSiblingId)) {
        // assign new Id
        try {// w ww.j  a v  a  2s  .  c o m
            if (node instanceof IUserLayoutChannelDescription) {
                isChannel = true;
                node.setId(this.distributedLayoutStore.generateNewChannelSubscribeId(owner));
            } else {
                node.setId(this.distributedLayoutStore.generateNewFolderId(owner));
            }
        } catch (Exception e) {
            throw new PortalException("Exception encountered while "
                    + "generating new user layout node Id for  for " + owner.getAttribute(IPerson.USERNAME), e);
        }

        Document uld = getUserLayoutDOM();
        Element childElement = node.getXML(uld);
        Element parentElement = uld.getElementById(parentId);
        if (nextSiblingId == null) {
            parentElement.appendChild(childElement);
        } else {
            Node nextSibling = uld.getElementById(nextSiblingId);
            parentElement.insertBefore(childElement, nextSibling);
        }
        // register element id
        childElement.setIdAttribute(Constants.ATT_ID, true);
        childElement.setAttribute(Constants.ATT_ID, node.getId());
        this.updateCacheKey();

        // push into the user's real layout that gets persisted.
        HandlerUtils.createPlfNodeAndPath(childElement, isChannel, owner);

        // fire event
        final int layoutId = this.getLayoutId();
        if (isChannel) {
            this.channelsAdded = true;
            final String fname = ((IUserLayoutChannelDescription) node).getFunctionalName();
            this.portalEventFactory.publishPortletAddedToLayoutPortalEvent(this, this.owner, layoutId,
                    parent.getId(), fname);
        } else {
            this.portalEventFactory.publishFolderAddedToLayoutPortalEvent(this, this.owner, layoutId,
                    node.getId());
        }

        return node;
    }
    return null;
}