Search in sources :

Example 26 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class CreateSignatureTest method testXFilter2Signature.

@org.junit.Test
public void testXFilter2Signature() throws Exception {
    Document doc = db.newDocument();
    doc.appendChild(doc.createComment(" Comment before "));
    Element root = doc.createElementNS("", "RootElement");
    doc.appendChild(root);
    root.appendChild(doc.createTextNode("Some simple text\n"));
    // Sign
    XMLSignature sig = new XMLSignature(doc, null, XMLSignature.ALGO_ID_SIGNATURE_DSA);
    root.appendChild(sig.getElement());
    Transforms transforms = new Transforms(doc);
    String filter = "here()/ancestor::ds.Signature/parent::node()/descendant-or-self::*";
    XPath2FilterContainer xpathC = XPath2FilterContainer.newInstanceIntersect(doc, filter);
    xpathC.setXPathNamespaceContext("dsig-xpath", Transforms.TRANSFORM_XPATH2FILTER);
    Element node = xpathC.getElement();
    transforms.addTransform(Transforms.TRANSFORM_XPATH2FILTER, node);
    sig.addDocument("", transforms, Constants.ALGO_ID_DIGEST_SHA1);
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = null;
    if (BASEDIR != null && !"".equals(BASEDIR)) {
        fis = new FileInputStream(BASEDIR + SEP + "src/test/resources/org/apache/xml/security/samples/input/keystore.jks");
    } else {
        fis = new FileInputStream("src/test/resources/org/apache/xml/security/samples/input/keystore.jks");
    }
    ks.load(fis, "xmlsecurity".toCharArray());
    PrivateKey privateKey = (PrivateKey) ks.getKey("test", "xmlsecurity".toCharArray());
    sig.sign(privateKey);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    XMLUtils.outputDOMc14nWithComments(doc, bos);
    String signedDoc = new String(bos.toByteArray());
    // Now Verify
    try (InputStream is = new ByteArrayInputStream(signedDoc.getBytes())) {
        doc = db.parse(is);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignature signature = new XMLSignature(sigElement, "");
    assertTrue(signature.checkSignatureValue(ks.getCertificate("test").getPublicKey()));
}
Also used : XPath(javax.xml.xpath.XPath) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Document(org.w3c.dom.Document) KeyStore(java.security.KeyStore) FileInputStream(java.io.FileInputStream) XPathFactory(javax.xml.xpath.XPathFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSignature(org.apache.xml.security.signature.XMLSignature) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XPath2FilterContainer(org.apache.xml.security.transforms.params.XPath2FilterContainer)

Example 27 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class CreateSignatureTest method doVerify.

private void doVerify(String signedXML) throws Exception {
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(signedXML.getBytes())) {
        doc = db.parse(is);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignature signature = new XMLSignature(sigElement, "");
    KeyInfo ki = signature.getKeyInfo();
    if (ki == null) {
        throw new RuntimeException("No keyinfo");
    }
    PublicKey pk = signature.getKeyInfo().getPublicKey();
    if (pk == null) {
        throw new RuntimeException("No public key");
    }
    assertTrue(signature.checkSignatureValue(pk));
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) ByteArrayInputStream(java.io.ByteArrayInputStream) KeyInfo(org.apache.xml.security.keys.KeyInfo) ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) Document(org.w3c.dom.Document)

Example 28 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class ECDSASignatureTest method doVerify.

private void doVerify(InputStream is) throws Exception {
    org.w3c.dom.Document doc = this.db.parse(is);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignature signature = new XMLSignature(sigElement, "");
    signature.addResourceResolver(new XPointerResourceResolver(sigElement));
    KeyInfo ki = signature.getKeyInfo();
    if (ki == null) {
        throw new RuntimeException("No keyinfo");
    }
    X509Certificate cert = signature.getKeyInfo().getX509Certificate();
    if (cert == null) {
        throw new RuntimeException("No certificate");
    }
    assertTrue(signature.checkSignatureValue(cert));
}
Also used : XPath(javax.xml.xpath.XPath) Element(org.w3c.dom.Element) X509Certificate(java.security.cert.X509Certificate) XPathFactory(javax.xml.xpath.XPathFactory) KeyInfo(org.apache.xml.security.keys.KeyInfo) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature)

Example 29 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class XPointerResourceResolver method engineResolveURI.

@Override
public XMLSignatureInput engineResolveURI(ResourceResolverContext context) throws ResourceResolverException {
    String v = context.uriToResolve;
    if (v.charAt(0) != '#') {
        return null;
    }
    String xpURI;
    try {
        xpURI = URLDecoder.decode(v, "utf-8");
    } catch (UnsupportedEncodingException e) {
        LOG.warn("utf-8 not a valid encoding ", e);
        return null;
    }
    String[] parts = xpURI.substring(1).split("\\s");
    int i = 0;
    Map<String, String> namespaces = new HashMap<>();
    if (parts.length > 1) {
        for (; i < parts.length - 1; ++i) {
            if (!parts[i].endsWith(")") || !parts[i].startsWith(XNS_OPEN)) {
                return null;
            }
            String mapping = parts[i].substring(XNS_OPEN.length(), parts[i].length() - 1);
            int pos = mapping.indexOf('=');
            if (pos <= 0 || pos >= mapping.length() - 1) {
                throw new ResourceResolverException("malformed namespace part of XPointer expression", context.uriToResolve, context.baseUri);
            }
            namespaces.put(mapping.substring(0, pos), mapping.substring(pos + 1));
        }
    }
    try {
        Node node = null;
        NodeList nodes = null;
        // plain ID reference.
        if (i == 0 && !parts[i].startsWith(XP_OPEN)) {
            node = this.baseNode.getOwnerDocument().getElementById(parts[i]);
        } else {
            if (!parts[i].endsWith(")") || !parts[i].startsWith(XP_OPEN)) {
                return null;
            }
            String xpathExpr = parts[i].substring(XP_OPEN.length(), parts[i].length() - 1);
            XPathFactory xpf = XPathFactory.newInstance();
            XPath xpath = xpf.newXPath();
            DSNamespaceContext namespaceContext = new DSNamespaceContext(namespaces);
            xpath.setNamespaceContext(namespaceContext);
            nodes = (NodeList) xpath.evaluate(xpathExpr, this.baseNode, XPathConstants.NODESET);
            if (nodes.getLength() == 0) {
                return null;
            }
            if (nodes.getLength() == 1) {
                node = nodes.item(0);
            }
        }
        XMLSignatureInput result = null;
        if (node != null) {
            result = new XMLSignatureInput(node);
        } else if (nodes != null) {
            Set<Node> nodeSet = new HashSet<>(nodes.getLength());
            for (int j = 0; j < nodes.getLength(); ++j) {
                nodeSet.add(nodes.item(j));
            }
            result = new XMLSignatureInput(nodeSet);
        } else {
            return null;
        }
        result.setMIMEType("text/xml");
        result.setExcludeComments(true);
        result.setSourceURI((context.baseUri != null) ? context.baseUri.concat(v) : v);
        return result;
    } catch (XPathExpressionException e) {
        throw new ResourceResolverException(e, context.uriToResolve, context.baseUri, "Problem evaluating XPath expression");
    }
}
Also used : XPath(javax.xml.xpath.XPath) Set(java.util.Set) HashSet(java.util.HashSet) HashMap(java.util.HashMap) XPathExpressionException(javax.xml.xpath.XPathExpressionException) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) UnsupportedEncodingException(java.io.UnsupportedEncodingException) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) ResourceResolverException(org.apache.xml.security.utils.resolver.ResourceResolverException) XPathFactory(javax.xml.xpath.XPathFactory) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext)

Example 30 with DSNamespaceContext

use of org.apache.xml.security.test.dom.DSNamespaceContext in project santuario-java by apache.

the class TransformBase64DecodeTest method test3.

@org.junit.Test
public void test3() throws Exception {
    // J-
    String input = "" + "<Object xmlns:signature='http://www.w3.org/2000/09/xmldsig#'>\n" + "<signature:Base64>\n" + "VGhlIFVSSSBvZiB0aGU gdHJhbn<RealText>Nmb  3JtIGlzIG<test/>h0dHA6</RealText>Ly93d3cudzMub3JnLzIwMDAvMDkveG1s\n" + "ZHNpZyNiYXNlNjQ=\n" + "</signature:Base64>\n" + "</Object>\n";
    // J+
    DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
    db.setErrorHandler(new org.apache.xml.security.utils.IgnoreAllErrorHandler());
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
        doc = db.parse(is);
    }
    // XMLUtils.circumventBug2650(doc);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//ds:Base64";
    Node base64Node = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
    XMLSignatureInput xmlinput = new XMLSignatureInput(base64Node);
    Document doc2 = TransformBase64DecodeTest.createDocument();
    Transforms t = new Transforms(doc2);
    doc2.appendChild(t.getElement());
    t.addTransform(Transforms.TRANSFORM_BASE64_DECODE);
    XMLSignatureInput out = t.performTransforms(xmlinput);
    String result = new String(out.getBytes());
    assertTrue("\"" + result + "\"", result.equals("The URI of the transform is http://www.w3.org/2000/09/xmldsig#base64"));
}
Also used : XPath(javax.xml.xpath.XPath) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Node(org.w3c.dom.Node) Transforms(org.apache.xml.security.transforms.Transforms) XMLSignatureInput(org.apache.xml.security.signature.XMLSignatureInput) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext)

Aggregations

XPath (javax.xml.xpath.XPath)37 XPathFactory (javax.xml.xpath.XPathFactory)37 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)37 Element (org.w3c.dom.Element)23 XMLSignature (org.apache.xml.security.signature.XMLSignature)18 Document (org.w3c.dom.Document)18 NodeList (org.w3c.dom.NodeList)14 ByteArrayInputStream (java.io.ByteArrayInputStream)11 InputStream (java.io.InputStream)11 DocumentBuilder (javax.xml.parsers.DocumentBuilder)11 KeyInfo (org.apache.xml.security.keys.KeyInfo)8 Node (org.w3c.dom.Node)8 File (java.io.File)7 X509Certificate (java.security.cert.X509Certificate)7 Transforms (org.apache.xml.security.transforms.Transforms)7 PublicKey (java.security.PublicKey)6 HashMap (java.util.HashMap)6 XMLCipher (org.apache.xml.security.encryption.XMLCipher)6 FileInputStream (java.io.FileInputStream)5 KeyStore (java.security.KeyStore)5