Search in sources :

Example 1 with InvalidCanonicalizerException

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

the class ApacheCanonicalizer method canonicalize.

public Data canonicalize(Data data, XMLCryptoContext xc, OutputStream os) throws TransformException {
    if (apacheCanonicalizer == null) {
        try {
            apacheCanonicalizer = Canonicalizer.getInstance(getAlgorithm());
            boolean secVal = Utils.secureValidation(xc);
            apacheCanonicalizer.setSecureValidation(secVal);
            LOG.debug("Created canonicalizer for algorithm: {}", getAlgorithm());
        } catch (InvalidCanonicalizerException ice) {
            throw new TransformException("Couldn't find Canonicalizer for: " + getAlgorithm() + ": " + ice.getMessage(), ice);
        }
    }
    if (os != null) {
        apacheCanonicalizer.setWriter(os);
    } else {
        apacheCanonicalizer.setWriter(new ByteArrayOutputStream());
    }
    try {
        Set<Node> nodeSet = null;
        if (data instanceof ApacheData) {
            XMLSignatureInput in = ((ApacheData) data).getXMLSignatureInput();
            if (in.isElement()) {
                if (inclusiveNamespaces != null) {
                    return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeSubtree(in.getSubNode(), inclusiveNamespaces)));
                } else {
                    return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeSubtree(in.getSubNode())));
                }
            } else if (in.isNodeSet()) {
                nodeSet = in.getNodeSet();
            } else {
                return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalize(Utils.readBytesFromStream(in.getOctetStream()))));
            }
        } else if (data instanceof DOMSubTreeData) {
            DOMSubTreeData subTree = (DOMSubTreeData) data;
            if (inclusiveNamespaces != null) {
                return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeSubtree(subTree.getRoot(), inclusiveNamespaces)));
            } else {
                return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeSubtree(subTree.getRoot())));
            }
        } else if (data instanceof NodeSetData) {
            NodeSetData nsd = (NodeSetData) data;
            // convert Iterator to Set
            @SuppressWarnings("unchecked") Set<Node> ns = Utils.toNodeSet(nsd.iterator());
            nodeSet = ns;
            LOG.debug("Canonicalizing {} nodes", nodeSet.size());
        } else {
            return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalize(Utils.readBytesFromStream(((OctetStreamData) data).getOctetStream()))));
        }
        if (inclusiveNamespaces != null) {
            return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeXPathNodeSet(nodeSet, inclusiveNamespaces)));
        } else {
            return new OctetStreamData(new ByteArrayInputStream(apacheCanonicalizer.canonicalizeXPathNodeSet(nodeSet)));
        }
    } catch (Exception e) {
        throw new TransformException(e);
    }
}
Also used : Node(org.w3c.dom.Node) TransformException(javax.xml.crypto.dsig.TransformException) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvalidAlgorithmParameterException(java.security.InvalidAlgorithmParameterException) TransformException(javax.xml.crypto.dsig.TransformException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) ByteArrayInputStream(java.io.ByteArrayInputStream) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException)

Example 2 with InvalidCanonicalizerException

use of org.apache.xml.security.c14n.InvalidCanonicalizerException 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)

Example 3 with InvalidCanonicalizerException

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

the class Reference method getContentsAfterTransformation.

private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os) throws XMLSignatureException {
    try {
        Transforms transforms = this.getTransforms();
        XMLSignatureInput output = null;
        if (transforms != null) {
            output = transforms.performTransforms(input, os);
            // new XMLSignatureInput(output.getBytes());
            this.transformsOutput = output;
        // this.transformsOutput.setSourceURI(output.getSourceURI());
        } else {
            output = input;
        }
        return output;
    } catch (ResourceResolverException ex) {
        throw new XMLSignatureException(ex);
    } catch (CanonicalizationException ex) {
        throw new XMLSignatureException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new XMLSignatureException(ex);
    } catch (TransformationException ex) {
        throw new XMLSignatureException(ex);
    } catch (XMLSecurityException ex) {
        throw new XMLSignatureException(ex);
    }
}
Also used : TransformationException(org.apache.xml.security.transforms.TransformationException) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) Transforms(org.apache.xml.security.transforms.Transforms) ResourceResolverException(org.apache.xml.security.utils.resolver.ResourceResolverException) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException)

Example 4 with InvalidCanonicalizerException

use of org.apache.xml.security.c14n.InvalidCanonicalizerException in project cxf by apache.

the class SymmetricBindingHandler method doEncryption.

private WSSecEncrypt doEncryption(AbstractTokenWrapper recToken, SecurityToken encrTok, boolean attached, List<WSEncryptionPart> encrParts, boolean atEnd, SecretKey symmetricKey) {
    AbstractToken encrToken = recToken.getToken();
    assertPolicy(recToken);
    assertPolicy(encrToken);
    try {
        WSSecEncrypt encr = new WSSecEncrypt(secHeader);
        encr.setEncryptionSerializer(new StaxSerializer());
        encr.setIdAllocator(wssConfig.getIdAllocator());
        encr.setCallbackLookup(callbackLookup);
        encr.setAttachmentCallbackHandler(new AttachmentCallbackHandler(message));
        encr.setStoreBytesInAttachment(storeBytesInAttachment);
        encr.setExpandXopInclude(isExpandXopInclude());
        encr.setWsDocInfo(wsDocInfo);
        String encrTokId = encrTok.getId();
        if (attached) {
            encrTokId = encrTok.getWsuId();
            if (encrTokId == null && (encrToken instanceof SecureConversationToken || encrToken instanceof SecurityContextToken)) {
                encr.setEncKeyIdDirectId(true);
                encrTokId = encrTok.getId();
            } else if (encrTokId == null) {
                encrTokId = encrTok.getId();
            }
            if (encrTokId.startsWith("#")) {
                encrTokId = encrTokId.substring(1);
            }
        } else {
            encr.setEncKeyIdDirectId(true);
        }
        if (encrTok.getTokenType() != null) {
            encr.setCustomReferenceValue(encrTok.getTokenType());
        }
        encr.setEncKeyId(encrTokId);
        AlgorithmSuite algorithmSuite = sbinding.getAlgorithmSuite();
        encr.setSymmetricEncAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryption());
        Crypto crypto = getEncryptionCrypto();
        if (crypto != null) {
            setEncryptionUser(encr, encrToken, false, crypto);
        }
        encr.setEncryptSymmKey(false);
        encr.setMGFAlgorithm(algorithmSuite.getAlgorithmSuiteType().getMGFAlgo());
        encr.setDigestAlgorithm(algorithmSuite.getAlgorithmSuiteType().getEncryptionDigest());
        if (encrToken instanceof IssuedToken || encrToken instanceof SpnegoContextToken || encrToken instanceof SecureConversationToken) {
            // Setting the AttachedReference or the UnattachedReference according to the flag
            Element ref;
            if (attached) {
                ref = encrTok.getAttachedReference();
            } else {
                ref = encrTok.getUnattachedReference();
            }
            String tokenType = encrTok.getTokenType();
            if (ref != null) {
                SecurityTokenReference secRef = new SecurityTokenReference(cloneElement(ref), new BSPEnforcer());
                encr.setSecurityTokenReference(secRef);
            } else if (WSS4JConstants.WSS_SAML_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML_NS.equals(tokenType)) {
                encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML_KI_VALUE_TYPE);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else if (WSS4JConstants.WSS_SAML2_TOKEN_TYPE.equals(tokenType) || WSS4JConstants.SAML2_NS.equals(tokenType)) {
                encr.setCustomReferenceValue(WSS4JConstants.WSS_SAML2_KI_VALUE_TYPE);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            } else {
                encr.setCustomReferenceValue(tokenType);
                encr.setKeyIdentifierType(WSConstants.CUSTOM_KEY_IDENTIFIER);
            }
        } else if (encrToken instanceof UsernameToken) {
            encr.setCustomReferenceValue(WSS4JConstants.WSS_USERNAME_TOKEN_VALUE_TYPE);
        } else if (encrToken instanceof KerberosToken && !isRequestor()) {
            encr.setCustomReferenceValue(WSS4JConstants.WSS_KRB_KI_VALUE_TYPE);
            encr.setEncKeyId(encrTok.getSHA1());
        } else if (!isRequestor() && encrTok.getSHA1() != null) {
            encr.setCustomReferenceValue(encrTok.getSHA1());
            encr.setKeyIdentifierType(WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER);
        }
        encr.prepare(crypto, symmetricKey);
        if (encr.getBSTTokenId() != null) {
            encr.prependBSTElementToHeader();
        }
        Element refList = encr.encryptForRef(null, encrParts, symmetricKey);
        List<Element> attachments = encr.getAttachmentEncryptedDataElements();
        addAttachmentsForEncryption(atEnd, refList, attachments);
        return encr;
    } catch (InvalidCanonicalizerException | WSSecurityException e) {
        LOG.log(Level.FINE, e.getMessage(), e);
        unassertPolicy(recToken, e);
    }
    return null;
}
Also used : WSSecEncrypt(org.apache.wss4j.dom.message.WSSecEncrypt) KerberosToken(org.apache.wss4j.policy.model.KerberosToken) IssuedToken(org.apache.wss4j.policy.model.IssuedToken) Element(org.w3c.dom.Element) UsernameToken(org.apache.wss4j.policy.model.UsernameToken) WSSecUsernameToken(org.apache.wss4j.dom.message.WSSecUsernameToken) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) SecureConversationToken(org.apache.wss4j.policy.model.SecureConversationToken) SpnegoContextToken(org.apache.wss4j.policy.model.SpnegoContextToken) AlgorithmSuite(org.apache.wss4j.policy.model.AlgorithmSuite) StaxSerializer(org.apache.cxf.ws.security.wss4j.StaxSerializer) Crypto(org.apache.wss4j.common.crypto.Crypto) AbstractToken(org.apache.wss4j.policy.model.AbstractToken) SecurityTokenReference(org.apache.wss4j.common.token.SecurityTokenReference) SecurityContextToken(org.apache.wss4j.policy.model.SecurityContextToken) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) AttachmentCallbackHandler(org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)

Example 5 with InvalidCanonicalizerException

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

the class XPath2NodeFilter method enginePerformTransform.

/**
 * Method enginePerformTransform
 * {@inheritDoc}
 * @param input
 *
 * @throws TransformationException
 */
protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, OutputStream os, Transform transformObject) throws TransformationException {
    try {
        List<NodeList> unionNodes = new ArrayList<>();
        List<NodeList> subtractNodes = new ArrayList<>();
        List<NodeList> intersectNodes = new ArrayList<>();
        Element[] xpathElements = XMLUtils.selectNodes(transformObject.getElement().getFirstChild(), XPath2FilterContainer.XPathFilter2NS, XPath2FilterContainer._TAG_XPATH2);
        if (xpathElements.length == 0) {
            Object[] exArgs = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" };
            throw new TransformationException("xml.WrongContent", exArgs);
        }
        Document inputDoc = null;
        if (input.getSubNode() != null) {
            inputDoc = XMLUtils.getOwnerDocument(input.getSubNode());
        } else {
            inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet());
        }
        for (int i = 0; i < xpathElements.length; i++) {
            Element xpathElement = xpathElements[i];
            XPath2FilterContainer xpathContainer = XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI());
            String str = XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode());
            XPathFactory xpathFactory = XPathFactory.newInstance();
            XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI();
            NodeList subtreeRoots = xpathAPIInstance.selectNodeList(inputDoc, xpathContainer.getXPathFilterTextNode(), str, xpathContainer.getElement());
            if (xpathContainer.isIntersect()) {
                intersectNodes.add(subtreeRoots);
            } else if (xpathContainer.isSubtract()) {
                subtractNodes.add(subtreeRoots);
            } else if (xpathContainer.isUnion()) {
                unionNodes.add(subtreeRoots);
            }
        }
        input.addNodeFilter(new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes));
        input.setNodeSet(true);
        return input;
    } catch (TransformerException ex) {
        throw new TransformationException(ex);
    } catch (DOMException ex) {
        throw new TransformationException(ex);
    } catch (CanonicalizationException ex) {
        throw new TransformationException(ex);
    } catch (InvalidCanonicalizerException ex) {
        throw new TransformationException(ex);
    } catch (XMLSecurityException ex) {
        throw new TransformationException(ex);
    } catch (SAXException ex) {
        throw new TransformationException(ex);
    } catch (IOException ex) {
        throw new TransformationException(ex);
    } catch (ParserConfigurationException ex) {
        throw new TransformationException(ex);
    }
}
Also used : TransformationException(org.apache.xml.security.transforms.TransformationException) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) XPathAPI(org.apache.xml.security.utils.XPathAPI) SAXException(org.xml.sax.SAXException) XPathFactory(org.apache.xml.security.utils.XPathFactory) DOMException(org.w3c.dom.DOMException) InvalidCanonicalizerException(org.apache.xml.security.c14n.InvalidCanonicalizerException) XPath2FilterContainer(org.apache.xml.security.transforms.params.XPath2FilterContainer) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) TransformerException(javax.xml.transform.TransformerException)

Aggregations

InvalidCanonicalizerException (org.apache.xml.security.c14n.InvalidCanonicalizerException)8 CanonicalizationException (org.apache.xml.security.c14n.CanonicalizationException)4 XMLSecurityException (org.apache.xml.security.exceptions.XMLSecurityException)4 Element (org.w3c.dom.Element)4 IOException (java.io.IOException)3 WSSecurityException (org.apache.wss4j.common.ext.WSSecurityException)3 TransformationException (org.apache.xml.security.transforms.TransformationException)3 PublicKey (java.security.PublicKey)2 AttachmentCallbackHandler (org.apache.cxf.ws.security.wss4j.AttachmentCallbackHandler)2 StaxSerializer (org.apache.cxf.ws.security.wss4j.StaxSerializer)2 Crypto (org.apache.wss4j.common.crypto.Crypto)2 WSSecEncrypt (org.apache.wss4j.dom.message.WSSecEncrypt)2 AbstractToken (org.apache.wss4j.policy.model.AbstractToken)2 AlgorithmSuite (org.apache.wss4j.policy.model.AlgorithmSuite)2 Transforms (org.apache.xml.security.transforms.Transforms)2 ByteArrayInputStream (java.io.ByteArrayInputStream)1 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1 OutputStream (java.io.OutputStream)1 InvalidAlgorithmParameterException (java.security.InvalidAlgorithmParameterException)1 Certificate (java.security.cert.Certificate)1