Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

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

/**
 * Creates and adds a Created element to this UsernameToken
 *///from w  ww .  ja  va2  s . c o m
public void addCreated(boolean milliseconds, Document doc) {
    if (elementCreated != null) {
        return;
    }
    DateFormat zulu = null;
    if (milliseconds) {
        zulu = new XmlSchemaDateFormat();
    } else {
        zulu = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        zulu.setTimeZone(TimeZone.getTimeZone("UTC"));
    }
    Calendar rightNow = Calendar.getInstance();
    elementCreated = doc.createElementNS(WSConstants.WSU_NS,
            WSConstants.WSU_PREFIX + ":" + WSConstants.CREATED_LN);
    WSSecurityUtil.setNamespace(element, WSConstants.WSU_NS, WSConstants.WSU_PREFIX);
    elementCreated.appendChild(doc.createTextNode(zulu.format(rightNow.getTime())));
    element.appendChild(elementCreated);
}

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

/**
 * Adds and optionally creates a Salt element to this UsernameToken.
 * //from w  w w  . j a v a2  s  . c o m
 * If the <code>saltValue</code> is <code>null</code> the the method
 * generates a new salt. Otherwise it uses the the given value.
 * 
 * @param doc The Document for the UsernameToken
 * @param saltValue The salt to add, if null generate a new salt value
 * @param mac If <code>true</code> then an optionally generated value is
 *            usable for a MAC
 * @return Returns the added salt
 */
public byte[] addSalt(Document doc, byte[] saltValue, boolean mac) {
    if (saltValue == null) {
        saltValue = generateSalt(mac);
    }
    elementSalt = doc.createElementNS(WSConstants.WSSE11_NS,
            WSConstants.WSSE11_PREFIX + ":" + WSConstants.SALT_LN);
    WSSecurityUtil.setNamespace(this.element, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
    elementSalt.appendChild(doc.createTextNode(Base64.encode(saltValue)));
    element.appendChild(elementSalt);
    return saltValue;
}

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

/**
 * Creates and adds a Iteration element to this UsernameToken
 *///from  w ww  . j a va 2 s  . co  m
public void addIteration(Document doc, int iteration) {
    String text = "" + iteration;
    elementIteration = doc.createElementNS(WSConstants.WSSE11_NS,
            WSConstants.WSSE11_PREFIX + ":" + WSConstants.ITERATION_LN);
    WSSecurityUtil.setNamespace(element, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
    this.elementIteration.appendChild(doc.createTextNode(text));
    element.appendChild(elementIteration);
}

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

/**
 * Create DOM subtree for <code>xenc:EncryptedKey</code>
 * //from   w  w  w.j a v  a  2s .c  om
 * @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 createCipherValue(Document doc, Element encryptedKey) {
    Element cipherData = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherData");
    Element cipherValue = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":CipherValue");
    cipherData.appendChild(cipherValue);
    encryptedKey.appendChild(cipherData);
    return cipherValue;
}

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 w  w w. ja v a2s . co  m
    encryptedKey.appendChild(referenceList);
    return referenceList;
}

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

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

private Vector doEncryption(Document doc, SecretKey secretKey, KeyInfo keyInfo, Vector references)
        throws WSSecurityException {

    XMLCipher xmlCipher = null;//from ww w. ja v a2 s .c  o m
    try {
        xmlCipher = XMLCipher.getInstance(symEncAlgo);
    } catch (XMLEncryptionException e3) {
        throw new WSSecurityException(WSSecurityException.UNSUPPORTED_ALGORITHM, null, null, e3);
    }

    Vector encDataRef = new Vector();

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

        String idToEnc = encPart.getId();
        String elemName = encPart.getName();
        String nmSpace = encPart.getNamespace();
        String modifier = encPart.getEncModifier();
        //
        // Third step: get the data to encrypt.
        //
        Element body = null;
        if (idToEnc != null) {
            body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, WSConstants.WSU_NS);
            if (body == null) {
                body = WSSecurityUtil.findElementById(document.getDocumentElement(), idToEnc, null);
            }
        } else {
            body = (Element) WSSecurityUtil.findElement(document, 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);
        encPart.setEncId(xencEncryptedDataId);

        cloneKeyInfo = true;

        if (keyInfo == null) {
            keyInfo = new KeyInfo(document);
            SecurityTokenReference secToken = new SecurityTokenReference(document);

            if (useKeyIdentifier && SecurityTokenReference.SAML_ID_URI.equals(customReferenceValue)) {
                secToken.setSAMLKeyIdentifier((encKeyIdDirectId ? "" : "#") + encKeyId);
            } else {
                Reference ref = new Reference(document);
                if (encKeyIdDirectId) {
                    ref.setURI(encKeyId);
                } else {
                    ref.setURI("#" + encKeyId);
                }
                if (encKeyValueType != null) {
                    ref.setValueType(encKeyValueType);
                }
                secToken.setReference(ref);
            }

            keyInfo.addUnknownElement(secToken.getElement());
            Element keyInfoElement = keyInfo.getElement();
            keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX,
                    WSConstants.SIG_NS);
        }
        //
        // Fourth step: encrypt data, and set necessary attributes in
        // xenc:EncryptedData
        //
        try {
            if (modifier.equals("Header")) {

                Element elem = doc.createElementNS(WSConstants.WSSE11_NS,
                        "wsse11:" + WSConstants.ENCRYPTED_HEADER);
                WSSecurityUtil.setNamespace(elem, WSConstants.WSSE11_NS, WSConstants.WSSE11_PREFIX);
                String wsuPrefix = WSSecurityUtil.setNamespace(elem, WSConstants.WSU_NS,
                        WSConstants.WSU_PREFIX);
                elem.setAttributeNS(WSConstants.WSU_NS, wsuPrefix + ":Id",
                        wssConfig.getIdAllocator().createId("EncHeader-", body));

                NamedNodeMap map = body.getAttributes();

                for (int i = 0; i < map.getLength(); i++) {
                    Attr attr = (Attr) map.item(i);
                    if (attr.getNamespaceURI().equals(WSConstants.URI_SOAP11_ENV)
                            || attr.getNamespaceURI().equals(WSConstants.URI_SOAP12_ENV)) {
                        String soapEnvPrefix = WSSecurityUtil.setNamespace(elem, attr.getNamespaceURI(),
                                WSConstants.DEFAULT_SOAP_PREFIX);
                        elem.setAttributeNS(attr.getNamespaceURI(), soapEnvPrefix + ":" + attr.getLocalName(),
                                attr.getValue());
                    }
                }

                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);

                Element encDataElem = WSSecurityUtil.findElementById(document.getDocumentElement(),
                        xencEncryptedDataId, null);
                Node clone = encDataElem.cloneNode(true);
                elem.appendChild(clone);
                encDataElem.getParentNode().appendChild(elem);
                encDataElem.getParentNode().removeChild(encDataElem);
            } else {
                xmlCipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
                EncryptedData encData = xmlCipher.getEncryptedData();
                encData.setId(xencEncryptedDataId);
                encData.setKeyInfo(keyInfo);
                xmlCipher.doFinal(doc, body, content);
            }
            if (cloneKeyInfo) {
                keyInfo = new KeyInfo((Element) keyInfo.getElement().cloneNode(true), null);
            }
        } catch (Exception e2) {
            throw new WSSecurityException(WSSecurityException.FAILED_ENCRYPTION, null, null, e2);
        }
        encDataRef.add("#" + xencEncryptedDataId);
    }
    return encDataRef;
}

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

private Document buildEmbedded(Document doc, WSSecHeader secHeader) throws WSSecurityException {
    doDebug = log.isDebugEnabled();//  ww w  . j  a  va2s.com

    if (doDebug) {
        log.debug("Beginning Encryption embedded...");
    }
    envelope = doc.getDocumentElement();
    envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.ENC_PREFIX, WSConstants.ENC_NS);

    //
    // Second step: generate a symmetric key from the specified key
    // (password) for this algorithm, and set the cipher into encryption
    // mode.
    //
    if (this.symmetricKey == null) {
        if (embeddedKey == null) {
            throw new WSSecurityException(WSSecurityException.FAILURE, "noKeySupplied");
        }
        this.symmetricKey = 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());
        }
    }
    Element keyInfoElement = keyInfo.getElement();
    keyInfoElement.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:" + WSConstants.SIG_PREFIX, WSConstants.SIG_NS);

    SOAPConstants soapConstants = WSSecurityUtil.getSOAPConstants(envelope);
    if (parts == null) {
        parts = new Vector();
        WSEncryptionPart encP = new WSEncryptionPart(soapConstants.getBodyQName().getLocalPart(),
                soapConstants.getEnvelopeURI(), "Content");
        parts.add(encP);
    }
    Vector encDataRefs = doEncryption(doc, this.symmetricKey, keyInfo, parts);

    //
    // 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
    //
    Element wsseSecurity = secHeader.getSecurityHeader();

    Element referenceList = doc.createElementNS(WSConstants.ENC_NS, WSConstants.ENC_PREFIX + ":ReferenceList");
    referenceList = createDataRefList(doc, referenceList, encDataRefs);
    WSSecurityUtil.prependChildElement(wsseSecurity, referenceList);

    return doc;
}

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

/**
 * Create DOM subtree for <code>xenc:EncryptedKey</code>
 * //  w  ww  . ja va  2  s  .c  om
 * @param doc the SOAP envelope parent document
 * @param referenceList
 * @param encDataRefs
 * @return an <code>xenc:EncryptedKey</code> element
 */
public static Element createDataRefList(Document doc, Element referenceList, Vector encDataRefs) {
    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);
    }
    return referenceList;
}