Search in sources :

Example 16 with DSNamespaceContext

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

the class SignatureVerificationReferenceURIResolverTest method testSignatureVerificationWithSameDocumentXPointerIdDoubleQuoteReference.

@Test
public void testSignatureVerificationWithSameDocumentXPointerIdDoubleQuoteReference() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), "default".toCharArray());
    Key key = keyStore.getKey("transmitter", "default".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//*[local-name()='ShippingAddress']";
    Element elementToSign = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(elementToSign);
    String id = UUID.randomUUID().toString();
    elementToSign.setAttributeNS(null, "Id", id);
    elementToSign.setIdAttributeNS(null, "Id", true);
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    ReferenceInfo referenceInfo = new ReferenceInfo("#xpointer(id(\"" + id + "\"))", new String[] { "http://www.w3.org/2001/10/xml-exc-c14n#" }, "http://www.w3.org/2000/09/xmldsig#sha1", false);
    List<ReferenceInfo> referenceInfos = new ArrayList<>();
    referenceInfos.add(referenceInfo);
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos);
    // Add KeyInfo
    sig.addKeyInfo(cert);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(cert.getPublicKey());
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
    StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) XMLSignature(org.apache.xml.security.signature.XMLSignature) XPath(javax.xml.xpath.XPath) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) Key(java.security.Key) Test(org.junit.Test)

Example 17 with DSNamespaceContext

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

the class XMLEncryption11Test method retrieveCCNumber.

/**
 * Method retrieveCCNumber
 * <p></p>
 * Retrieve the credit card number from the payment info document
 *
 * @param doc The document to retrieve the card number from
 * @return The retrieved credit card number
 * @throws javax.xml.xpath.XPathExpressionException
 */
private static String retrieveCCNumber(Document doc) throws javax.xml.transform.TransformerException, XPathExpressionException {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    Map<String, String> namespace = new HashMap<>();
    namespace.put("x", "urn:example:po");
    DSNamespaceContext context = new DSNamespaceContext(namespace);
    xpath.setNamespaceContext(context);
    String expression = "//x:Number/text()";
    Node ccnumElt = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
    if (ccnumElt != null) {
        return ccnumElt.getNodeValue();
    }
    return null;
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) HashMap(java.util.HashMap) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Node(org.w3c.dom.Node)

Example 18 with DSNamespaceContext

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

the class AbstractSignatureCreationTest method getxPath.

private XPath getxPath() {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    return xpath;
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext)

Example 19 with DSNamespaceContext

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

the class SignatureCreationTest method testMultipleSignatures.

@Test
public void testMultipleSignatures() throws Exception {
    // Set up the Configuration
    XMLSecurityProperties properties = new XMLSecurityProperties();
    List<XMLSecurityConstants.Action> actions = new ArrayList<XMLSecurityConstants.Action>();
    actions.add(XMLSecurityConstants.SIGNATURE);
    properties.setActions(actions);
    // Set the key up
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), "default".toCharArray());
    Key key = keyStore.getKey("transmitter", "default".toCharArray());
    properties.setSignatureKey(key);
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
    properties.setSignatureCerts(new X509Certificate[] { cert });
    SecurePart securePart = new SecurePart(new QName("urn:example:po", "PaymentInfo"), SecurePart.Modifier.Content);
    properties.addSignaturePart(securePart);
    OutboundXMLSec outboundXMLSec = XMLSec.getOutboundXMLSec(properties);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XMLStreamWriter xmlStreamWriter = outboundXMLSec.processOutMessage(baos, StandardCharsets.UTF_8.name());
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
    XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
    xmlStreamWriter.close();
    // Now do second signature
    sourceDocument = new ByteArrayInputStream(baos.toByteArray());
    outboundXMLSec = XMLSec.getOutboundXMLSec(properties);
    baos = new ByteArrayOutputStream();
    xmlStreamWriter = outboundXMLSec.processOutMessage(baos, StandardCharsets.UTF_8.name());
    xmlStreamReader = xmlInputFactory.createXMLStreamReader(sourceDocument);
    XmlReaderToWriter.writeAll(xmlStreamReader, xmlStreamWriter);
    xmlStreamWriter.close();
    // System.out.println("Got:\n" + new String(baos.toByteArray(), StandardCharsets.UTF_8.name()));
    Document document = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        document = XMLUtils.createDocumentBuilder(false).parse(is);
    }
    // Verify using DOM
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//dsig:Signature";
    NodeList sigElements = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
    Assert.assertTrue(sigElements.getLength() == 2);
    for (SecurePart secPart : properties.getSignatureSecureParts()) {
        if (secPart.getName() == null) {
            continue;
        }
        expression = "//*[local-name()='" + secPart.getName().getLocalPart() + "']";
        Element signedElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
        Assert.assertNotNull(signedElement);
        signedElement.setIdAttributeNS(null, "Id", true);
    }
    for (int i = 0; i < sigElements.getLength(); i++) {
        XMLSignature signature = new XMLSignature((Element) sigElements.item(i), "");
        Assert.assertTrue(signature.checkSignatureValue(cert));
    }
}
Also used : XMLStreamReader(javax.xml.stream.XMLStreamReader) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) XMLStreamWriter(javax.xml.stream.XMLStreamWriter) XMLSignature(org.apache.xml.security.signature.XMLSignature) XPath(javax.xml.xpath.XPath) QName(javax.xml.namespace.QName) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) ByteArrayOutputStream(java.io.ByteArrayOutputStream) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) ByteArrayInputStream(java.io.ByteArrayInputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Key(java.security.Key) SecretKey(javax.crypto.SecretKey) Test(org.junit.Test)

Example 20 with DSNamespaceContext

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

the class SignatureVerificationReferenceURIResolverTest method testSignatureVerificationWithSameDocumentXPointerIdApostropheReference.

@Test
public void testSignatureVerificationWithSameDocumentXPointerIdApostropheReference() throws Exception {
    // Read in plaintext document
    InputStream sourceDocument = this.getClass().getClassLoader().getResourceAsStream("ie/baltimore/merlin-examples/merlin-xmlenc-five/plaintext.xml");
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = builder.parse(sourceDocument);
    // Set up the Key
    KeyStore keyStore = KeyStore.getInstance("jks");
    keyStore.load(this.getClass().getClassLoader().getResource("transmitter.jks").openStream(), "default".toCharArray());
    Key key = keyStore.getKey("transmitter", "default".toCharArray());
    X509Certificate cert = (X509Certificate) keyStore.getCertificate("transmitter");
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//*[local-name()='ShippingAddress']";
    Element elementToSign = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(elementToSign);
    String id = UUID.randomUUID().toString();
    elementToSign.setAttributeNS(null, "Id", id);
    elementToSign.setIdAttributeNS(null, "Id", true);
    // Sign using DOM
    List<String> localNames = new ArrayList<>();
    localNames.add("PaymentInfo");
    ReferenceInfo referenceInfo = new ReferenceInfo("#xpointer(id('" + id + "'))", new String[] { "http://www.w3.org/2001/10/xml-exc-c14n#" }, "http://www.w3.org/2000/09/xmldsig#sha1", false);
    List<ReferenceInfo> referenceInfos = new ArrayList<>();
    referenceInfos.add(referenceInfo);
    XMLSignature sig = signUsingDOM("http://www.w3.org/2000/09/xmldsig#rsa-sha1", document, localNames, key, referenceInfos);
    // Add KeyInfo
    sig.addKeyInfo(cert);
    // Convert Document to a Stream Reader
    javax.xml.transform.Transformer transformer = transformerFactory.newTransformer();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    transformer.transform(new DOMSource(document), new StreamResult(baos));
    XMLStreamReader xmlStreamReader = null;
    try (InputStream is = new ByteArrayInputStream(baos.toByteArray())) {
        xmlStreamReader = xmlInputFactory.createXMLStreamReader(is);
    }
    // Verify signature
    XMLSecurityProperties properties = new XMLSecurityProperties();
    properties.setSignatureVerificationKey(cert.getPublicKey());
    InboundXMLSec inboundXMLSec = XMLSec.getInboundWSSec(properties);
    XMLStreamReader securityStreamReader = inboundXMLSec.processInMessage(xmlStreamReader);
    StAX2DOM.readDoc(XMLUtils.createDocumentBuilder(false), securityStreamReader);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) XMLStreamReader(javax.xml.stream.XMLStreamReader) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) XMLSignature(org.apache.xml.security.signature.XMLSignature) XPath(javax.xml.xpath.XPath) StreamResult(javax.xml.transform.stream.StreamResult) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InboundXMLSec(org.apache.xml.security.stax.ext.InboundXMLSec) KeyStore(java.security.KeyStore) X509Certificate(java.security.cert.X509Certificate) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSecurityProperties(org.apache.xml.security.stax.ext.XMLSecurityProperties) Key(java.security.Key) Test(org.junit.Test)

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