Search in sources :

Example 6 with CanonicalizationException

use of org.apache.xml.security.c14n.CanonicalizationException in project santuario-java by apache.

the class CanonicalizerBase method canonicalizeXPathNodeSet.

/**
 * Canonicalizes all the nodes included in the currentNode and contained in the
 * xpathNodeSet field.
 *
 * @param currentNode
 * @param endnode
 * @throws CanonicalizationException
 * @throws IOException
 */
protected final void canonicalizeXPathNodeSet(Node currentNode, Node endnode) throws CanonicalizationException, IOException {
    if (isVisibleInt(currentNode) == -1) {
        return;
    }
    boolean currentNodeIsVisible = false;
    NameSpaceSymbTable ns = new NameSpaceSymbTable();
    if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) {
        getParentNameSpaces((Element) currentNode, ns);
    }
    if (currentNode == null) {
        return;
    }
    Node sibling = null;
    Node parentNode = null;
    int documentLevel = NODE_BEFORE_DOCUMENT_ELEMENT;
    Map<String, byte[]> cache = new HashMap<>();
    do {
        switch(currentNode.getNodeType()) {
            case Node.ENTITY_NODE:
            case Node.NOTATION_NODE:
            case Node.ATTRIBUTE_NODE:
                // illegal node type during traversal
                throw new CanonicalizationException("empty", new Object[] { "illegal node type during traversal" });
            case Node.DOCUMENT_FRAGMENT_NODE:
            case Node.DOCUMENT_NODE:
                ns.outputNodePush();
                sibling = currentNode.getFirstChild();
                break;
            case Node.COMMENT_NODE:
                if (this.includeComments && isVisibleDO(currentNode, ns.getLevel()) == 1) {
                    outputCommentToWriter((Comment) currentNode, writer, documentLevel);
                }
                break;
            case Node.PROCESSING_INSTRUCTION_NODE:
                if (isVisible(currentNode)) {
                    outputPItoWriter((ProcessingInstruction) currentNode, writer, documentLevel);
                }
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                if (isVisible(currentNode)) {
                    outputTextToWriter(currentNode.getNodeValue(), writer);
                    for (Node nextSibling = currentNode.getNextSibling(); nextSibling != null && (nextSibling.getNodeType() == Node.TEXT_NODE || nextSibling.getNodeType() == Node.CDATA_SECTION_NODE); nextSibling = nextSibling.getNextSibling()) {
                        outputTextToWriter(nextSibling.getNodeValue(), writer);
                        currentNode = nextSibling;
                        sibling = currentNode.getNextSibling();
                    }
                }
                break;
            case Node.ELEMENT_NODE:
                documentLevel = NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT;
                Element currentElement = (Element) currentNode;
                // Add a level to the nssymbtable. So latter can be pop-back.
                String name = null;
                int i = isVisibleDO(currentNode, ns.getLevel());
                if (i == -1) {
                    sibling = currentNode.getNextSibling();
                    break;
                }
                currentNodeIsVisible = i == 1;
                if (currentNodeIsVisible) {
                    ns.outputNodePush();
                    writer.write('<');
                    name = currentElement.getTagName();
                    UtfHelpper.writeByte(name, writer, cache);
                } else {
                    ns.push();
                }
                outputAttributes(currentElement, ns, cache);
                if (currentNodeIsVisible) {
                    writer.write('>');
                }
                sibling = currentNode.getFirstChild();
                if (sibling == null) {
                    if (currentNodeIsVisible) {
                        writer.write(END_TAG.clone());
                        UtfHelpper.writeByte(name, writer, cache);
                        writer.write('>');
                        // We finished with this level, pop to the previous definitions.
                        ns.outputNodePop();
                    } else {
                        ns.pop();
                    }
                    if (parentNode != null) {
                        sibling = currentNode.getNextSibling();
                    }
                } else {
                    parentNode = currentElement;
                }
                break;
            case Node.DOCUMENT_TYPE_NODE:
            default:
                break;
        }
        while (sibling == null && parentNode != null) {
            if (isVisible(parentNode)) {
                writer.write(END_TAG.clone());
                UtfHelpper.writeByte(((Element) parentNode).getTagName(), writer, cache);
                writer.write('>');
                // We finished with this level, pop to the previous definitions.
                ns.outputNodePop();
            } else {
                ns.pop();
            }
            if (parentNode == endnode) {
                return;
            }
            sibling = parentNode.getNextSibling();
            parentNode = parentNode.getParentNode();
            if (parentNode == null || Node.ELEMENT_NODE != parentNode.getNodeType()) {
                parentNode = null;
                documentLevel = NODE_AFTER_DOCUMENT_ELEMENT;
            }
        }
        if (sibling == null) {
            return;
        }
        currentNode = sibling;
        sibling = currentNode.getNextSibling();
    } while (true);
}
Also used : HashMap(java.util.HashMap) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element)

Example 7 with CanonicalizationException

use of org.apache.xml.security.c14n.CanonicalizationException in project santuario-java by apache.

the class XMLCipherInput method getDecryptBytes.

/**
 * Internal method to get bytes in decryption mode
 * @return the decrypted bytes
 * @throws XMLEncryptionException
 */
private byte[] getDecryptBytes() throws XMLEncryptionException {
    String base64EncodedEncryptedOctets = null;
    if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) {
        // Fun time!
        LOG.debug("Found a reference type CipherData");
        CipherReference cr = cipherData.getCipherReference();
        // Need to wrap the uri in an Attribute node so that we can
        // Pass to the resource resolvers
        Attr uriAttr = cr.getURIAsAttr();
        XMLSignatureInput input = null;
        try {
            ResourceResolver resolver = ResourceResolver.getInstance(uriAttr, null, secureValidation);
            input = resolver.resolve(uriAttr, null, secureValidation);
        } catch (ResourceResolverException ex) {
            throw new XMLEncryptionException(ex);
        }
        if (input != null) {
            LOG.debug("Managed to resolve URI \"{}\"", cr.getURI());
        } else {
            LOG.debug("Failed to resolve URI \"{}\"", cr.getURI());
        }
        // Lets see if there are any transforms
        Transforms transforms = cr.getTransforms();
        if (transforms != null) {
            LOG.debug("Have transforms in cipher reference");
            try {
                org.apache.xml.security.transforms.Transforms dsTransforms = transforms.getDSTransforms();
                dsTransforms.setSecureValidation(secureValidation);
                input = dsTransforms.performTransforms(input);
            } catch (TransformationException ex) {
                throw new XMLEncryptionException(ex);
            }
        }
        try {
            return input.getBytes();
        } catch (IOException ex) {
            throw new XMLEncryptionException(ex);
        } catch (CanonicalizationException ex) {
            throw new XMLEncryptionException(ex);
        }
    // retrieve the cipher text
    } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) {
        base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue();
    } else {
        throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value");
    }
    LOG.debug("Encrypted octets:\n{}", base64EncodedEncryptedOctets);
    return Base64.getMimeDecoder().decode(base64EncodedEncryptedOctets);
}
Also used : TransformationException(org.apache.xml.security.transforms.TransformationException) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) ResourceResolverException(org.apache.xml.security.utils.resolver.ResourceResolverException) IOException(java.io.IOException) Attr(org.w3c.dom.Attr) ResourceResolver(org.apache.xml.security.utils.resolver.ResourceResolver)

Example 8 with CanonicalizationException

use of org.apache.xml.security.c14n.CanonicalizationException in project santuario-java by apache.

the class TransformC14NExclusive method enginePerformTransform.

protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, OutputStream os, Transform transformObject) throws CanonicalizationException {
    try {
        String inclusiveNamespaces = null;
        if (transformObject.length(InclusiveNamespaces.ExclusiveCanonicalizationNamespace, InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1) {
            Element inclusiveElement = XMLUtils.selectNode(transformObject.getElement().getFirstChild(), InclusiveNamespaces.ExclusiveCanonicalizationNamespace, InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, 0);
            inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces();
        }
        Canonicalizer20010315ExclOmitComments c14n = new Canonicalizer20010315ExclOmitComments();
        c14n.setSecureValidation(secureValidation);
        if (os != null) {
            c14n.setWriter(os);
        }
        byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces);
        XMLSignatureInput output = new XMLSignatureInput(result);
        output.setSecureValidation(secureValidation);
        if (os != null) {
            output.setOutputStream(os);
        }
        return output;
    } catch (XMLSecurityException ex) {
        throw new CanonicalizationException(ex);
    }
}
Also used : CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) Element(org.w3c.dom.Element) InclusiveNamespaces(org.apache.xml.security.transforms.params.InclusiveNamespaces) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) Canonicalizer20010315ExclOmitComments(org.apache.xml.security.c14n.implementations.Canonicalizer20010315ExclOmitComments) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 9 with CanonicalizationException

use of org.apache.xml.security.c14n.CanonicalizationException in project santuario-java by apache.

the class Transform method performTransform.

/**
 * Transforms the input, and generates {@link XMLSignatureInput} as output.
 *
 * @param input input {@link XMLSignatureInput} which can supplied Octect
 * Stream and NodeSet as Input of Transformation
 * @param os where to output the result of the last transformation
 * @return the {@link XMLSignatureInput} class as the result of
 * transformation
 * @throws CanonicalizationException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws TransformationException
 */
public XMLSignatureInput performTransform(XMLSignatureInput input, OutputStream os) throws IOException, CanonicalizationException, InvalidCanonicalizerException, TransformationException {
    XMLSignatureInput result = null;
    try {
        transformSpi.secureValidation = secureValidation;
        result = transformSpi.enginePerformTransform(input, os, this);
    } catch (ParserConfigurationException ex) {
        Object[] exArgs = { this.getURI(), "ParserConfigurationException" };
        throw new CanonicalizationException(ex, "signature.Transform.ErrorDuringTransform", exArgs);
    } catch (SAXException ex) {
        Object[] exArgs = { this.getURI(), "SAXException" };
        throw new CanonicalizationException(ex, "signature.Transform.ErrorDuringTransform", exArgs);
    }
    return result;
}
Also used : CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXException(org.xml.sax.SAXException)

Example 10 with CanonicalizationException

use of org.apache.xml.security.c14n.CanonicalizationException in project santuario-java by apache.

the class XMLSignature method sign.

/**
 * Digests all References in the SignedInfo, calculates the signature value
 * and sets it in the SignatureValue Element.
 *
 * @param signingKey the {@link java.security.PrivateKey} or
 * {@link javax.crypto.SecretKey} that is used to sign.
 * @throws XMLSignatureException
 */
public void sign(Key signingKey) throws XMLSignatureException {
    if (signingKey instanceof PublicKey) {
        throw new IllegalArgumentException(I18n.translate("algorithms.operationOnlyVerification"));
    }
    // Create a SignatureAlgorithm object
    SignedInfo si = this.getSignedInfo();
    SignatureAlgorithm sa = si.getSignatureAlgorithm();
    try (SignerOutputStream output = new SignerOutputStream(sa);
        OutputStream so = new UnsyncBufferedOutputStream(output)) {
        // generate digest values for all References in this SignedInfo
        si.generateDigestValues();
        // initialize SignatureAlgorithm for signing
        sa.initSign(signingKey);
        // get the canonicalized bytes from SignedInfo
        si.signInOctetStream(so);
        // set them on the SignatureValue element
        this.setSignatureValueElement(sa.sign());
    } catch (XMLSignatureException ex) {
        throw ex;
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException(ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    } catch (IOException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) PublicKey(java.security.PublicKey) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) SignerOutputStream(org.apache.xml.security.utils.SignerOutputStream) OutputStream(java.io.OutputStream) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) SignatureAlgorithm(org.apache.xml.security.algorithms.SignatureAlgorithm) IOException(java.io.IOException) UnsyncBufferedOutputStream(org.apache.xml.security.utils.UnsyncBufferedOutputStream) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Aggregations

CanonicalizationException (org.apache.xml.security.c14n.CanonicalizationException)18 IOException (java.io.IOException)6 OutputStream (java.io.OutputStream)6 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)6 Attr (org.w3c.dom.Attr)5 Element (org.w3c.dom.Element)5 NamedNodeMap (org.w3c.dom.NamedNodeMap)5 Node (org.w3c.dom.Node)5 TreeSet (java.util.TreeSet)4 InvalidCanonicalizerException (org.apache.xml.security.c14n.InvalidCanonicalizerException)4 XMLSignatureInput (org.apache.xml.security.signature.XMLSignatureInput)4 TransformationException (org.apache.xml.security.transforms.TransformationException)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 UnsyncByteArrayOutputStream (org.apache.xml.security.utils.UnsyncByteArrayOutputStream)3 ResourceResolverException (org.apache.xml.security.utils.resolver.ResourceResolverException)3 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 HashMap (java.util.HashMap)2 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)2 Transforms (org.apache.xml.security.transforms.Transforms)2 InclusiveNamespaces (org.apache.xml.security.transforms.params.InclusiveNamespaces)2