Example usage for org.w3c.dom Element setAttributeNS

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

Introduction

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

Prototype

public void setAttributeNS(String namespaceURI, String qualifiedName, String value) throws DOMException;

Source Link

Document

Adds a new attribute.

Usage

From source file:org.apache.ws.security.message.token.SecurityTokenReferenceTest.java

/**
 * Test for a SecurityTokenReference having a Key Identifier with a bad EncodingType
 *///ww w . j  a  v a  2 s .  com
@org.junit.Test
public void testKeyIdentifierBadEncodingType() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    // Create the STR
    SecurityTokenReference str = new SecurityTokenReference(doc);
    str.addWSSENamespace();
    Element strElement = str.getElement();

    Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
    keyId.setAttributeNS(null, "ValueType", SecurityTokenReference.ENC_KEY_SHA1_URI);
    keyId.setAttributeNS(null, "EncodingType", "http://bad_encoding");
    keyId.appendChild(doc.createTextNode("#123"));
    strElement.appendChild(keyId);

    if (LOG.isDebugEnabled()) {
        LOG.debug(str.toString());
    }

    // Process the STR
    try {
        new SecurityTokenReference(strElement);
        fail("Failure expected on a Key Identifier with a Bad EncodingType");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getMessage().contains("bad EncodingType"));
    }

    new SecurityTokenReference(strElement, false);
}

From source file:org.apache.ws.security.message.token.SecurityTokenReferenceTest.java

/**
 * Test for a SecurityTokenReference having a Key Identifier with no EncodingType
 *//*from w  ww.j av a  2s  .  c  om*/
@org.junit.Test
public void testKeyIdentifierNoEncodingType() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    // Create the STR
    SecurityTokenReference str = new SecurityTokenReference(doc);
    str.addWSSENamespace();
    Element strElement = str.getElement();

    Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
    keyId.setAttributeNS(null, "ValueType", SecurityTokenReference.ENC_KEY_SHA1_URI);
    keyId.appendChild(doc.createTextNode("#123"));
    strElement.appendChild(keyId);

    if (LOG.isDebugEnabled()) {
        LOG.debug(str.toString());
    }

    // Process the STR
    try {
        new SecurityTokenReference(strElement);
        fail("Failure expected on a Key Identifier with no EncodingType");
    } catch (WSSecurityException ex) {
        assertTrue(ex.getMessage().contains("No EncodingType"));
    }

    new SecurityTokenReference(strElement, false);
}

From source file:org.apache.ws.security.message.token.SecurityTokenReferenceTest.java

/**
 * Test for a SecurityTokenReference having a Key Identifier with no EncodingType, but
 * it should pass as the ValueType is for a SAML Assertion.
 *//*from w  ww  .j a va2s. com*/
@org.junit.Test
public void testKeyIdentifierSAMLNoEncodingType() throws Exception {
    Document doc = SOAPUtil.toSOAPPart(SOAPUtil.SAMPLE_SOAP_MSG);

    // Create the STR
    SecurityTokenReference str = new SecurityTokenReference(doc);
    str.addWSSENamespace();
    Element strElement = str.getElement();

    Element keyId = doc.createElementNS(WSConstants.WSSE_NS, "wsse:KeyIdentifier");
    keyId.setAttributeNS(null, "ValueType", WSConstants.WSS_SAML_KI_VALUE_TYPE);
    keyId.appendChild(doc.createTextNode("#123"));
    strElement.appendChild(keyId);

    if (LOG.isDebugEnabled()) {
        LOG.debug(str.toString());
    }

    // Process the STR
    new SecurityTokenReference(strElement);
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

private Vector doEncryption(Document doc, SecretKey encryptKey, KeyInfo keyInfo) throws WSSecurityException {
    /*//from   www .jav a  2  s  .c  om
     * First step: set the encryption encoding namespace in the SOAP:Envelope
     */
    Element envelope = doc.getDocumentElement();
    envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);

    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);

    XMLCipher xmlCipher = null;
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
    } catch (XMLEncryptionException e3) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
    }

    // if no encryption parts set - use the default
    if (parts == null) {
        parts = new Vector();
        WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content");
        parts.add(encP);
    }

    Vector encDataRefs = new Vector();

    for (int part = 0; part < parts.size(); part++) {
        WSEncryptionPart encPart = (WSEncryptionPart) parts.get(part);
        String elemName = encPart.getName();
        String nmSpace = encPart.getNamespace();
        String modifier = encPart.getEncModifier();
        /*
         * Third step: get the data to encrypt.
         */
        Element body = (Element) WSSecurityUtil.findElement(envelope, elemName, nmSpace);
        if (body == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                    new Object[] { "{" + nmSpace + "}" + elemName });
        }

        boolean content = modifier.equals("Content") ? true : false;
        String xencEncryptedDataId = wssConfig.getIdAllocator().createId("EncDataId-", body);

        /*
         * Forth step: encrypt data, and set neccessary attributes in
         * xenc:EncryptedData
         */
        try {
            xmlCipher.init(XMLCipher.ENCRYPT_MODE, encryptKey);
            EncryptedData encData = xmlCipher.getEncryptedData();
            encData.setId(xencEncryptedDataId);
            encData.setKeyInfo(keyInfo);
            xmlCipher.doFinal(doc, body, content);
        } catch (Exception e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e2);
        }
        encDataRefs.add(new String("#" + xencEncryptedDataId));
    }
    return encDataRefs;
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

private Document buildEmbedded(Document doc) throws WSSecurityException {
    doDebug = log.isDebugEnabled();/*from   w ww.j  av  a  2s.  c o  m*/

    long t0 = 0, t1 = 0;
    if (tlog.isDebugEnabled()) {
        t0 = System.currentTimeMillis();
    }
    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }

    /*
     * Second step: generate a symmetric key from the specified
     * key (password) for this algorithm, and set the cipher into
     * encryption mode.
     */
    this.encryptionKey = this.symmetricKey;
    if (this.encryptionKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.encryptionKey = WSSecurityUtil.prepareSecretKey(symEncAlgo, embeddedKey);
    }

    KeyInfo keyInfo = null;
    if (this.keyIdentifierType == WSConstants.EMBEDDED_KEYNAME) {
        keyInfo = new KeyInfo(doc);
        keyInfo.addKeyName(embeddedKeyName == null ? user : embeddedKeyName);
    } else if (this.keyIdentifierType == WSConstants.EMBED_SECURITY_TOKEN_REF) {
        /* This means that we want to embed a <wsse:SecurityTokenReference>
        * into keyInfo element.
        * If we need this functionality, this.secRef MUST be set before
        * calling the build(doc, crypto) method.
        * So if secRef is null then throw an exception.
        */
        if (this.securityTokenReference == null) {
            throw new WSSecurityException(WSSecurityException.SECURITY_TOKEN_UNAVAILABLE,
                    "You must set keyInfo element, if the keyIdentifier " + "== EMBED_SECURITY_TOKEN_REF");
        } else {
            keyInfo = new KeyInfo(doc);
            Element tmpE = securityTokenReference.getElement();
            tmpE.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + tmpE.getPrefix(), tmpE.getNamespaceURI());
            keyInfo.addUnknownElement(securityTokenReference.getElement());
        }
    }

    Vector encDataRefs = doEncryption(doc, this.encryptionKey, keyInfo);

    /*
     * At this point data is encrypted with the symmetric key and can be
     * referenced via the above Id
     */

    /*
     * Now we need to setup the wsse:Security header block
     * 1) get (or create) the wsse:Security header block
     * 2) The last step sets up the reference list that pints to the encrypted
     *    data that was encrypted with this encrypted session key :-)
     */
    Element wsseSecurity = insertSecurityHeader(doc);

    Element tmpE = doc.createElement("temp");
    Element refList = createDataRefList(doc, tmpE, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, refList);

    if (tlog.isDebugEnabled()) {
        tlog.debug("EncryptBody embedded: symm-enc " + (t1 - t0));
    }
    return doc;
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

/**
 * Create DOM subtree for <code>xenc:EncryptedKey</code>
 * // w w w  .  j  a v a  2s  .  co m
 * @param doc
 *            the SOAP envelope parent document
 * @param keyTransportAlgo
 *            specifies which algorithm to use to encrypt the symmetric key
 * @return an <code>xenc:EncryptedKey</code> element
 */
public static Element createEncryptedKey(Document doc, String keyTransportAlgo) {
    Element encryptedKey = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":EncryptedKey");

    WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS, WSConstants.ENC_PREFIX);
    Element encryptionMethod = doc.createElementNS(WSConstants.ENC_NS,
            WSConstants.ENC_PREFIX + ":EncryptionMethod");
    encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo);
    encryptedKey.appendChild(encryptionMethod);
    return encryptedKey;
}

From source file:org.apache.ws.security.message.WSEncryptBody.java

public static Element createDataRefList(Document doc, Element encryptedKey, Vector encDataRefs) {
    Element referenceList = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":ReferenceList");
    for (int i = 0; i < encDataRefs.size(); i++) {
        String dataReferenceUri = (String) encDataRefs.get(i);
        Element dataReference = doc.createElementNS(WSConstants.ENC_NS,
                WSConstants.ENC_PREFIX + ":DataReference");
        dataReference.setAttributeNS(null, "URI", dataReferenceUri);
        referenceList.appendChild(dataReference);
    }/*from   www.j  a  v  a 2 s.co m*/
    encryptedKey.appendChild(referenceList);
    return referenceList;
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

public void prepare(Document doc, WSSecHeader secHeader) throws WSSecurityException, ConversationException {
    super.prepare(doc);
    wsDocInfo = new WSDocInfo(doc);

    ////from   w  ww . j  a v  a 2s  . c  om
    // Get and initialize a XMLSignature element.
    //
    if (canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
        Element canonElem = XMLUtils.createElementInSignatureSpace(doc, Constants._TAG_CANONICALIZATIONMETHOD);

        canonElem.setAttributeNS(null, Constants._ATT_ALGORITHM, canonAlgo);

        if (wssConfig.isWsiBSPCompliant()) {
            Set prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            InclusiveNamespaces inclusiveNamespaces = new InclusiveNamespaces(doc, prefixes);
            canonElem.appendChild(inclusiveNamespaces.getElement());
        }

        try {
            SignatureAlgorithm signatureAlgorithm = new SignatureAlgorithm(doc, sigAlgo);
            sig = new XMLSignature(doc, null, signatureAlgorithm.getElement(), canonElem);
        } catch (XMLSecurityException e) {
            log.error("", e);
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e);
        }
    } else {
        try {
            sig = new XMLSignature(doc, null, sigAlgo, canonAlgo);
        } catch (XMLSecurityException e) {
            log.error("", e);
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e);
        }
    }

    sig.addResourceResolver(EnvelopeIdResolver.getInstance());
    String sigUri = wssConfig.getIdAllocator().createId("Signature-", sig);
    sig.setId(sigUri);

    keyInfo = sig.getKeyInfo();
    keyInfoUri = wssConfig.getIdAllocator().createSecureId("KeyId-", keyInfo);
    keyInfo.setId(keyInfoUri);

    secRef = new SecurityTokenReference(doc);
    strUri = wssConfig.getIdAllocator().createSecureId("STRId-", secRef);
    secRef.setID(strUri);

    Reference refUt = new Reference(document);
    refUt.setURI("#" + this.dktId);
    secRef.setReference(refUt);

    keyInfo.addUnknownElement(secRef.getElement());
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

/**
 * This method adds references to the Signature.
 * /* w  w  w . j a  v  a2 s  .  co  m*/
 * The added references are signed when calling
 * <code>computeSignature()</code>. This method can be called several
 * times to add references as required. <code>addReferencesToSign()</code>
 * can be called any time after <code>prepare</code>.
 * 
 * @param references A vector containing <code>WSEncryptionPart</code> objects
 *                   that define the parts to sign.
 * @param secHeader Used to compute namespaces to be inserted by
 *                  InclusiveNamespaces to be WSI compliant.
 * @throws WSSecurityException
 */
public void addReferencesToSign(Vector references, WSSecHeader secHeader) throws WSSecurityException {
    Transforms transforms = null;

    Element envel = document.getDocumentElement();

    for (int part = 0; part < references.size(); part++) {
        WSEncryptionPart encPart = (WSEncryptionPart) references.get(part);

        String idToSign = encPart.getId();
        String elemName = encPart.getName();
        String nmSpace = encPart.getNamespace();

        //
        // Set up the elements to sign. There are two reserved element
        // names: "Token" and "STRTransform" "Token": Setup the Signature to
        // either sign the information that points to the security token or
        // the token itself. If its a direct reference sign the token,
        // otherwise sign the KeyInfo Element. "STRTransform": Setup the
        // ds:Reference to use STR Transform
        // 
        transforms = new Transforms(document);
        try {
            if (idToSign != null) {
                Element toSignById = WSSecurityUtil.findElementById(document.getDocumentElement(), idToSign,
                        WSConstants.WSU_NS);
                if (toSignById == null) {
                    toSignById = WSSecurityUtil.findElementById(document.getDocumentElement(), idToSign, null);
                }
                transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                if (wssConfig.isWsiBSPCompliant()) {
                    transforms.item(0).getElement().appendChild(
                            new InclusiveNamespaces(document, getInclusivePrefixes(toSignById)).getElement());
                }
                sig.addDocument("#" + idToSign, transforms);
            } else if (elemName.equals("Token")) {
                transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                if (wssConfig.isWsiBSPCompliant()) {
                    transforms.item(0).getElement().appendChild(
                            new InclusiveNamespaces(document, getInclusivePrefixes(keyInfo.getElement()))
                                    .getElement());
                }
                sig.addDocument("#" + keyInfoUri, transforms);
            } else if (elemName.equals("STRTransform")) { // STRTransform
                Element ctx = createSTRParameter(document);
                transforms.addTransform(STRTransform.implementedTransformURI, ctx);
                sig.addDocument("#" + strUri, transforms);
            } else if (elemName.equals("Assertion")) { // Assertion
                String id = SAMLUtil.getAssertionId(envel, elemName, nmSpace);

                Element body = (Element) WSSecurityUtil.findElement(envel, elemName, nmSpace);
                if (body == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                            new Object[] { nmSpace + ", " + elemName });
                }
                transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                if (wssConfig.isWsiBSPCompliant()) {
                    transforms.item(0).getElement().appendChild(
                            new InclusiveNamespaces(document, getInclusivePrefixes(body)).getElement());
                }
                String prefix = WSSecurityUtil.setNamespace(body, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
                body.setAttributeNS(WSConstants.WSU_NS, prefix + ":Id", id);
                sig.addDocument("#" + id, transforms);

            } else {
                Element body = (Element) WSSecurityUtil.findElement(envel, elemName, nmSpace);
                if (body == null) {
                    throw new WSSecurityException(WSSecurityException.FAILURE, "noEncElement",
                            new Object[] { nmSpace + ", " + elemName });
                }
                transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
                if (wssConfig.isWsiBSPCompliant()) {
                    transforms.item(0).getElement().appendChild(
                            new InclusiveNamespaces(document, getInclusivePrefixes(body)).getElement());
                }
                sig.addDocument("#" + setWsuId(body), transforms);
            }
        } catch (TransformationException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1);
        } catch (XMLSignatureException e1) {
            throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, e1);
        }
    }
}

From source file:org.apache.ws.security.message.WSSecDKSign.java

protected Element createSTRParameter(Document doc) {
    Element transformParam = doc.createElementNS(WSConstants.WSSE_NS,
            WSConstants.WSSE_PREFIX + ":TransformationParameters");

    WSSecurityUtil.setNamespace(transformParam, WSConstants.WSSE_NS, WSConstants.WSSE_PREFIX);

    Element canonElem = doc.createElementNS(WSConstants.SIG_NS,
            WSConstants.SIG_PREFIX + ":CanonicalizationMethod");

    WSSecurityUtil.setNamespace(canonElem, WSConstants.SIG_NS, WSConstants.SIG_PREFIX);

    canonElem.setAttributeNS(null, "Algorithm", Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS);
    transformParam.appendChild(canonElem);
    return transformParam;
}