Java Code Examples for org.apache.xml.security.encryption.XMLEncryptionException

The following examples show how to use org.apache.xml.security.encryption.XMLEncryptionException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: cxf   Source File: StaxSerializer.java    License: Apache License 2.0 6 votes vote down vote up
private XMLStreamReader createWstxReader(byte[] source, Node ctx) throws XMLEncryptionException {
    try {
        if (factory == null) {
            factory = StaxUtils.createXMLInputFactory(true);
            try {
                factory.setProperty("com.ctc.wstx.fragmentMode",
                                    com.ctc.wstx.api.WstxInputProperties.PARSING_MODE_FRAGMENT);
                factory.setProperty(org.codehaus.stax2.XMLInputFactory2.P_REPORT_PROLOG_WHITESPACE, Boolean.TRUE);
                validFactory = true;
            } catch (Throwable t) {
                //ignore
                validFactory = false;
            }
        }
        if (validFactory) {
            XMLStreamReader reader = factory.createXMLStreamReader(new ByteArrayInputStream(source));
            if (addNamespaces(reader, ctx)) {
                return reader;
            }
        }
    } catch (Throwable e) {
        //ignore
    }
    return null;
}
 
Example 2
Source Project: cxf   Source File: StaxSerializer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param source
 * @param ctx
 * @return the Node resulting from the parse of the source
 * @throws XMLEncryptionException
 */
@Override
public Node deserialize(byte[] source, Node ctx) throws XMLEncryptionException {
    XMLStreamReader reader = createWstxReader(source, ctx);
    if (reader != null) {
        return deserialize(ctx, reader, false);
    }
    return deserialize(ctx, new InputSource(createStreamContext(source, ctx)));
}
 
Example 3
Source Project: cxf   Source File: EncryptionUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static XMLCipher initXMLCipher(String symEncAlgo, int mode, Key key)
    throws WSSecurityException {
    try {
        XMLCipher cipher = XMLCipher.getInstance(symEncAlgo);
        cipher.setSecureValidation(true);
        cipher.init(mode, key);
        return cipher;
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, ex);
    }
}
 
Example 4
Source Project: cxf   Source File: SAMLProtocolResponseValidator.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] decryptPayload(
    Element root, byte[] secretKeyBytes, String symEncAlgo
) throws WSSecurityException {
    SecretKey key = KeyUtils.prepareSecretKey(symEncAlgo, secretKeyBytes);
    try {
        XMLCipher xmlCipher =
            EncryptionUtils.initXMLCipher(symEncAlgo, XMLCipher.DECRYPT_MODE, key);
        return xmlCipher.decryptToByteArray(root);
    } catch (XMLEncryptionException ex) {
        throw new WSSecurityException(WSSecurityException.ErrorCode.UNSUPPORTED_ALGORITHM, ex);
    }
}
 
Example 5
Source Project: keycloak   Source File: XMLEncryptionUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * Encrypt the Key to be transported
 * </p>
 * <p>
 * Data is encrypted with a SecretKey. Then the key needs to be transported to the other end where it is needed for
 * decryption. For the Key transport, the SecretKey is encrypted with the recipient's public key. At the receiving
 * end, the
 * receiver can decrypt the Secret Key using his private key.s
 * </p>
 *
 * @param document
 * @param keyToBeEncrypted Symmetric Key (SecretKey)
 * @param keyUsedToEncryptSecretKey Asymmetric Key (Public Key)
 * @param keySize Length of the key
 *
 * @return
 *
 * @throws org.keycloak.saml.common.exceptions.ProcessingException
 */
public static EncryptedKey encryptKey(Document document, SecretKey keyToBeEncrypted, PublicKey keyUsedToEncryptSecretKey,
                                      int keySize) throws ProcessingException {
    XMLCipher keyCipher;
    String pubKeyAlg = keyUsedToEncryptSecretKey.getAlgorithm();

    try {
        String keyWrapAlgo = getXMLEncryptionURLForKeyUnwrap(pubKeyAlg, keySize);
        keyCipher = XMLCipher.getInstance(keyWrapAlgo);

        keyCipher.init(XMLCipher.WRAP_MODE, keyUsedToEncryptSecretKey);
        return keyCipher.encryptKey(document, keyToBeEncrypted);
    } catch (XMLEncryptionException e) {
        throw logger.processingError(e);
    }
}
 
Example 6
Source Project: cxf   Source File: StaxSerializer.java    License: Apache License 2.0 4 votes vote down vote up
private InputStream createStreamContext(byte[] source, Node ctx) throws XMLEncryptionException {
    Vector<InputStream> v = new Vector<>(2); //NOPMD

    LoadingByteArrayOutputStream byteArrayOutputStream = new LoadingByteArrayOutputStream();
    try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, UTF_8);
        outputStreamWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?><dummy");

        // Run through each node up to the document node and find any xmlns: nodes
        Map<String, String> storedNamespaces = new HashMap<>();
        Node wk = ctx;
        while (wk != null) {
            NamedNodeMap atts = wk.getAttributes();
            if (atts != null) {
                for (int i = 0; i < atts.getLength(); ++i) {
                    Node att = atts.item(i);
                    String nodeName = att.getNodeName();
                    if (("xmlns".equals(nodeName) || nodeName.startsWith("xmlns:"))
                            && !storedNamespaces.containsKey(att.getNodeName())) {
                        outputStreamWriter.write(" ");
                        outputStreamWriter.write(nodeName);
                        outputStreamWriter.write("=\"");
                        outputStreamWriter.write(att.getNodeValue());
                        outputStreamWriter.write("\"");
                        storedNamespaces.put(nodeName, att.getNodeValue());
                    }
                }
            }
            wk = wk.getParentNode();
        }
        outputStreamWriter.write(">");
        outputStreamWriter.close();
        v.add(byteArrayOutputStream.createInputStream());
        v.addElement(new ByteArrayInputStream(source));
        byteArrayOutputStream = new LoadingByteArrayOutputStream();
        outputStreamWriter = new OutputStreamWriter(byteArrayOutputStream, UTF_8);
        outputStreamWriter.write("</dummy>");
        outputStreamWriter.close();
        v.add(byteArrayOutputStream.createInputStream());
    } catch (IOException e) {
        throw new XMLEncryptionException(e);
    }
    return new SequenceInputStream(v.elements());
}
 
Example 7
Source Project: keycloak   Source File: XMLEncryptionUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Given an element in a Document, encrypt the element and replace the element in the document with the encrypted
 * data
 *
 * @param elementQName QName of the element that we like to encrypt
 * @param document
 * @param publicKey
 * @param secretKey
 * @param keySize
 * @param wrappingElementQName A QName of an element that will wrap the encrypted element
 * @param addEncryptedKeyInKeyInfo Need for the EncryptedKey to be placed in ds:KeyInfo
 *
 * @throws ProcessingException
 */
public static void encryptElement(QName elementQName, Document document, PublicKey publicKey, SecretKey secretKey,
                                  int keySize, QName wrappingElementQName, boolean addEncryptedKeyInKeyInfo) throws ProcessingException {
    if (elementQName == null)
        throw logger.nullArgumentError("elementQName");
    if (document == null)
        throw logger.nullArgumentError("document");
    String wrappingElementPrefix = wrappingElementQName.getPrefix();
    if (wrappingElementPrefix == null || "".equals(wrappingElementPrefix))
        throw logger.wrongTypeError("Wrapping element prefix invalid");

    Element documentElement = DocumentUtil.getElement(document, elementQName);

    if (documentElement == null)
        throw logger.domMissingDocElementError(elementQName.toString());

    XMLCipher cipher = null;
    EncryptedKey encryptedKey = encryptKey(document, secretKey, publicKey, keySize);

    String encryptionAlgorithm = getXMLEncryptionURL(secretKey.getAlgorithm(), keySize);
    // Encrypt the Document
    try {
        cipher = XMLCipher.getInstance(encryptionAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    } catch (XMLEncryptionException e1) {
        throw logger.processingError(e1);
    }

    Document encryptedDoc;
    try {
        encryptedDoc = cipher.doFinal(document, documentElement);
    } catch (Exception e) {
        throw logger.processingError(e);
    }

    // The EncryptedKey element is added
    Element encryptedKeyElement = cipher.martial(document, encryptedKey);

    final String wrappingElementName;

    if (StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElementName = wrappingElementQName.getLocalPart();
    } else {
        wrappingElementName = wrappingElementPrefix + ":" + wrappingElementQName.getLocalPart();
    }
    // Create the wrapping element and set its attribute NS
    Element wrappingElement = encryptedDoc.createElementNS(wrappingElementQName.getNamespaceURI(), wrappingElementName);

    if (! StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + wrappingElementPrefix, wrappingElementQName.getNamespaceURI());
    }

    // Get Hold of the Cipher Data
    NodeList cipherElements = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTEDDATA);
    if (cipherElements == null || cipherElements.getLength() == 0)
        throw logger.domMissingElementError("xenc:EncryptedData");
    Element encryptedDataElement = (Element) cipherElements.item(0);

    Node parentOfEncNode = encryptedDataElement.getParentNode();
    parentOfEncNode.replaceChild(wrappingElement, encryptedDataElement);

    wrappingElement.appendChild(encryptedDataElement);

    if (addEncryptedKeyInKeyInfo) {
        // Outer ds:KeyInfo Element to hold the EncryptionKey
        Element sigElement = encryptedDoc.createElementNS(XMLSignature.XMLNS, DS_KEY_INFO);
        sigElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:ds", XMLSignature.XMLNS);
        sigElement.appendChild(encryptedKeyElement);

        // Insert the Encrypted key before the CipherData element
        NodeList nodeList = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
        if (nodeList == null || nodeList.getLength() == 0)
            throw logger.domMissingElementError("xenc:CipherData");
        Element cipherDataElement = (Element) nodeList.item(0);
        Node cipherParent = cipherDataElement.getParentNode();
        cipherParent.insertBefore(sigElement, cipherDataElement);
    } else {
        // Add the encrypted key as a child of the wrapping element
        wrappingElement.appendChild(encryptedKeyElement);
    }
}
 
Example 8
Source Project: keycloak   Source File: XMLEncryptionUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * <p>
 * Encrypts an element in a XML document using the specified public key, secret key, and key size. This method
 * doesn't wrap
 * the encrypted element in a new element. Instead, it replaces the element with its encrypted version.
 * </p>
 * <p>
 * For example, calling this method to encrypt the <tt><b>inner</b></tt> element in the following XML document
 *
 * <pre>
 *    &lt;root&gt;
 *       &lt;outer&gt;
 *          &lt;inner&gt;
 *             ...
 *          &lt;/inner&gt;
 *       &lt;/outer&gt;
 *    &lt;/root&gt;
 * </pre>
 *
 * would result in a document similar to
 *
 * <pre>
 *    &lt;root&gt;
 *       &lt;outer&gt;
 *          &lt;xenc:EncryptedData xmlns:xenc="..."&gt;
 *             ...
 *          &lt;/xenc:EncryptedData&gt;
 *       &lt;/outer&gt;
 *    &lt;/root&gt;
 * </pre>
 *
 * </p>
 *
 * @param document the {@code Document} that contains the element to be encrypted.
 * @param element the {@code Element} to be encrypted.
 * @param publicKey the {@code PublicKey} that must be used to encrypt the secret key.
 * @param secretKey the {@code SecretKey} used to encrypt the specified element.
 * @param keySize the size (in bits) of the secret key.
 *
 * @throws ProcessingException if an error occurs while encrypting the element with the specified params.
 */
public static void encryptElement(Document document, Element element, PublicKey publicKey, SecretKey secretKey, int keySize)
        throws ProcessingException {
    if (element == null)
        throw logger.nullArgumentError("element");
    if (document == null)
        throw logger.nullArgumentError("document");

    XMLCipher cipher = null;
    EncryptedKey encryptedKey = encryptKey(document, secretKey, publicKey, keySize);
    String encryptionAlgorithm = getXMLEncryptionURL(secretKey.getAlgorithm(), keySize);

    // Encrypt the Document
    try {
        cipher = XMLCipher.getInstance(encryptionAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    } catch (XMLEncryptionException e1) {
        throw logger.processingError(e1);
    }

    Document encryptedDoc;
    try {
        encryptedDoc = cipher.doFinal(document, element);
    } catch (Exception e) {
        throw logger.processingError(e);
    }

    // The EncryptedKey element is added
    Element encryptedKeyElement = cipher.martial(document, encryptedKey);

    // Outer ds:KeyInfo Element to hold the EncryptionKey
    Element sigElement = encryptedDoc.createElementNS(XMLSignature.XMLNS, DS_KEY_INFO);
    sigElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:ds", XMLSignature.XMLNS);
    sigElement.appendChild(encryptedKeyElement);

    // Insert the Encrypted key before the CipherData element
    NodeList nodeList = encryptedDoc.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
    if (nodeList == null || nodeList.getLength() == 0)
        throw logger.domMissingElementError("xenc:CipherData");
    Element cipherDataElement = (Element) nodeList.item(0);
    Node cipherParent = cipherDataElement.getParentNode();
    cipherParent.insertBefore(sigElement, cipherDataElement);
}
 
Example 9
Source Project: keycloak   Source File: XMLEncryptionUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Encrypt the root document element inside a Document. <b>NOTE:</b> The document root element will be replaced by
 * the
 * wrapping element.
 *
 * @param document Document that contains an element to encrypt
 * @param publicKey The Public Key used to encrypt the secret encryption key
 * @param secretKey The secret encryption key
 * @param keySize Length of key
 * @param wrappingElementQName QName of the element to be used to wrap around the cipher data.
 * @param addEncryptedKeyInKeyInfo Should the encrypted key be inside a KeyInfo or added as a peer of Cipher Data
 *
 * @return An element that has the wrappingElementQName
 *
 * @throws ProcessingException
 * @throws org.keycloak.saml.common.exceptions.ConfigurationException
 */
public static Element encryptElementInDocument(Document document, PublicKey publicKey, SecretKey secretKey, int keySize,
                                               QName wrappingElementQName, boolean addEncryptedKeyInKeyInfo) throws ProcessingException, ConfigurationException {
    String wrappingElementPrefix = wrappingElementQName.getPrefix();
    if (wrappingElementPrefix == null || "".equals(wrappingElementPrefix))
        throw logger.wrongTypeError("Wrapping element prefix invalid");

    XMLCipher cipher = null;
    EncryptedKey encryptedKey = encryptKey(document, secretKey, publicKey, keySize);

    String encryptionAlgorithm = getXMLEncryptionURL(secretKey.getAlgorithm(), keySize);
    // Encrypt the Document
    try {
        cipher = XMLCipher.getInstance(encryptionAlgorithm);
        cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    } catch (XMLEncryptionException e1) {
        throw logger.configurationError(e1);
    }

    Document encryptedDoc;
    try {
        encryptedDoc = cipher.doFinal(document, document.getDocumentElement());
    } catch (Exception e) {
        throw logger.processingError(e);
    }

    // The EncryptedKey element is added
    Element encryptedKeyElement = cipher.martial(document, encryptedKey);

    final String wrappingElementName;

    if (StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElementName = wrappingElementQName.getLocalPart();
    } else {
        wrappingElementName = wrappingElementPrefix + ":" + wrappingElementQName.getLocalPart();
    }
    // Create the wrapping element and set its attribute NS
    Element wrappingElement = encryptedDoc.createElementNS(wrappingElementQName.getNamespaceURI(), wrappingElementName);

    if (! StringUtil.isNullOrEmpty(wrappingElementPrefix)) {
        wrappingElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:" + wrappingElementPrefix, wrappingElementQName.getNamespaceURI());
    }

    Element encryptedDocRootElement = encryptedDoc.getDocumentElement();
    // Bring in the encrypted wrapping element to wrap the root node
    encryptedDoc.replaceChild(wrappingElement, encryptedDocRootElement);

    wrappingElement.appendChild(encryptedDocRootElement);

    if (addEncryptedKeyInKeyInfo) {
        // Outer ds:KeyInfo Element to hold the EncryptionKey
        Element sigElement = encryptedDoc.createElementNS(XMLSignature.XMLNS, DS_KEY_INFO);
        sigElement.setAttributeNS(XMLConstants.XMLNS_ATTRIBUTE_NS_URI, "xmlns:ds", XMLSignature.XMLNS);
        sigElement.appendChild(encryptedKeyElement);

        // Insert the Encrypted key before the CipherData element
        NodeList nodeList = encryptedDocRootElement.getElementsByTagNameNS(EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA);
        if (nodeList == null || nodeList.getLength() == 0)
            throw logger.domMissingElementError("xenc:CipherData");

        Element cipherDataElement = (Element) nodeList.item(0);
        encryptedDocRootElement.insertBefore(sigElement, cipherDataElement);
    } else {
        // Add the encrypted key as a child of the wrapping element
        wrappingElement.appendChild(encryptedKeyElement);
    }

    return encryptedDoc.getDocumentElement();
}
 
Example 10
Source Project: cxf   Source File: StaxSerializer.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * @param ctx
 * @param inputSource
 * @return the Node resulting from the parse of the source
 * @throws XMLEncryptionException
 */
private Node deserialize(Node ctx, InputSource inputSource) throws XMLEncryptionException {
    XMLStreamReader reader = StaxUtils.createXMLStreamReader(inputSource);
    return deserialize(ctx, reader, true);
}