Search in sources :

Example 1 with DSNamespaceContext

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

the class SignedEncryptedTest method secureAndVerify.

public void secureAndVerify(TransformerFactory transformerFactory, boolean useDocumentSerializer) throws Exception {
    DocumentBuilder builder = XMLUtils.createDocumentBuilder(false);
    Document document = null;
    try (InputStream is = new ByteArrayInputStream(SAMPLE_MSG.getBytes(StandardCharsets.UTF_8))) {
        document = builder.parse(is);
    }
    // Set up the Key
    KeyPairGenerator rsaKeygen = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = rsaKeygen.generateKeyPair();
    PrivateKey priv = kp.getPrivate();
    PublicKey pub = kp.getPublic();
    XMLSignature sig = new XMLSignature(document, "", XMLSignature.ALGO_ID_SIGNATURE_RSA_SHA1, Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    Element sigElement = sig.getElement();
    document.getDocumentElement().appendChild(sigElement);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    Element element = (Element) xpath.evaluate("//*[local-name()='Body']", document, XPathConstants.NODE);
    String id = UUID.randomUUID().toString();
    element.setAttributeNS(null, "Id", id);
    element.setIdAttributeNS(null, "Id", true);
    Transforms transforms = new Transforms(document);
    transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
    sig.addDocument("#" + id, transforms, Constants.ALGO_ID_DIGEST_SHA1);
    sig.addKeyInfo(pub);
    sig.sign(priv);
    KeyGenerator keygen = KeyGenerator.getInstance("AES");
    keygen.init(256);
    SecretKey secretKey = keygen.generateKey();
    XMLCipher cipher = XMLCipher.getInstance(XMLCipher.AES_128);
    cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    document = cipher.doFinal(document, element, true);
    XMLCipher deCipher = XMLCipher.getInstance(XMLCipher.AES_128);
    if (transformerFactory != null && deCipher.getSerializer() instanceof TransformSerializer) {
        Field f = deCipher.getSerializer().getClass().getDeclaredField("transformerFactory");
        f.setAccessible(true);
        f.set(deCipher.getSerializer(), transformerFactory);
    }
    if (useDocumentSerializer) {
        deCipher.setSerializer(new DocumentSerializer());
    }
    deCipher.init(XMLCipher.DECRYPT_MODE, secretKey);
    deCipher.doFinal(document, element, true);
    XMLSignature xmlSignatureVerifier = new XMLSignature(sigElement, "");
    Assert.assertTrue(xmlSignatureVerifier.checkSignatureValue(pub));
}
Also used : XPath(javax.xml.xpath.XPath) KeyPair(java.security.KeyPair) PrivateKey(java.security.PrivateKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) PublicKey(java.security.PublicKey) Element(org.w3c.dom.Element) Transforms(org.apache.xml.security.transforms.Transforms) XMLCipher(org.apache.xml.security.encryption.XMLCipher) KeyPairGenerator(java.security.KeyPairGenerator) Document(org.w3c.dom.Document) TransformSerializer(org.apache.xml.security.encryption.TransformSerializer) XPathFactory(javax.xml.xpath.XPathFactory) Field(java.lang.reflect.Field) SecretKey(javax.crypto.SecretKey) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) XMLSignature(org.apache.xml.security.signature.XMLSignature) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) DocumentSerializer(org.apache.xml.security.encryption.DocumentSerializer) KeyGenerator(javax.crypto.KeyGenerator)

Example 2 with DSNamespaceContext

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

the class HMACSignatureAlgorithmTest method verify.

private void verify(Document document, Key key, List<String> localNames, boolean secureValidation) throws Exception {
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    String expression = "//dsig:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(sigElement);
    for (String name : localNames) {
        expression = "//*[local-name()='" + name + "']";
        Element signedElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
        Assert.assertNotNull(signedElement);
        signedElement.setIdAttributeNS(null, "Id", true);
    }
    XMLSignature signature = new XMLSignature(sigElement, "", secureValidation);
    Assert.assertTrue(signature.checkSignatureValue(key));
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) XMLSignature(org.apache.xml.security.signature.XMLSignature) Element(org.w3c.dom.Element)

Example 3 with DSNamespaceContext

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

the class PKSignatureAlgorithmTest method sign.

private XMLSignature sign(String algorithm, Document document, List<String> localNames, Key signingKey) throws Exception {
    String c14nMethod = "http://www.w3.org/2001/10/xml-exc-c14n#";
    XMLSignature sig = new XMLSignature(document, "", algorithm, c14nMethod);
    Element root = document.getDocumentElement();
    root.appendChild(sig.getElement());
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    for (String localName : localNames) {
        String expression = "//*[local-name()='" + localName + "']";
        NodeList elementsToSign = (NodeList) xpath.evaluate(expression, document, XPathConstants.NODESET);
        for (int i = 0; i < elementsToSign.getLength(); i++) {
            Element elementToSign = (Element) elementsToSign.item(i);
            Assert.assertNotNull(elementToSign);
            String id = UUID.randomUUID().toString();
            elementToSign.setAttributeNS(null, "Id", id);
            elementToSign.setIdAttributeNS(null, "Id", true);
            Transforms transforms = new Transforms(document);
            transforms.addTransform(c14nMethod);
            String digestMethod = "http://www.w3.org/2000/09/xmldsig#sha1";
            sig.addDocument("#" + id, transforms, digestMethod);
        }
    }
    sig.sign(signingKey);
    String expression = "//ds:Signature[1]";
    Element sigElement = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
    Assert.assertNotNull(sigElement);
    return sig;
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) XMLSignature(org.apache.xml.security.signature.XMLSignature) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) Transforms(org.apache.xml.security.transforms.Transforms)

Example 4 with DSNamespaceContext

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

the class Canonicalizer20010315Test method test37byNodeList.

/**
 * 3.7 Document Subsets
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @see <A HREF="http://www.w3.org/TR/2001/PR-xml-c14n-20010119#Example-DocSubsets">the example from the spec</A>
 * @throws TransformerException
 * @throws XPathExpressionException
 */
@org.junit.Test
public void test37byNodeList() throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
    // String descri = "3.7 Document Subsets. (uncommented), c14n by NodeList";
    String fileIn = prefix + "in/37_input.xml";
    String fileRef = prefix + "in/37_c14n.xml";
    // String c14nURI = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS;
    // boolean validating = true;
    DocumentBuilder db = XMLUtils.createDocumentBuilder(false, false);
    org.xml.sax.EntityResolver resolver = new TestVectorResolver();
    db.setEntityResolver(resolver);
    Document doc = db.parse(resolver.resolveEntity(null, fileIn));
    String xpath = "(//. | //@* | //namespace::*)" + "[ " + "self::ietf:e1 or " + "(parent::ietf:e1 and not(self::text() or self::e2)) or " + "count(id(\"E3\")|ancestor-or-self::node()) = count(ancestor-or-self::node()) " + "]";
    Map<String, String> namespace = new HashMap<>();
    namespace.put("ietf", "http://www.ietf.org");
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xPath = xpf.newXPath();
    DSNamespaceContext namespaceContext = new DSNamespaceContext(namespace);
    xPath.setNamespaceContext(namespaceContext);
    NodeList nodes = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
    Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    byte[] c14nBytes = c14n.canonicalizeXPathNodeSet(nodes);
    InputStream refStream = resolver.resolveEntity(null, fileRef).getByteStream();
    byte[] refBytes = JavaUtils.getBytesFromStream(refStream);
    assertEquals(new String(refBytes), new String(c14nBytes));
}
Also used : XPath(javax.xml.xpath.XPath) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NodeList(org.w3c.dom.NodeList) TestVectorResolver(org.apache.xml.security.test.dom.resource.TestVectorResolver) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

Example 5 with DSNamespaceContext

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

the class Canonicalizer20010315Test method doTestXMLAttributes.

/**
 * Method doTestXMLAttributes
 *
 * @param input
 * @param definedOutput
 * @param writeResultsToFile
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 * @throws XPathExpressionException
 */
private boolean doTestXMLAttributes(String input, String definedOutput) throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
    DocumentBuilder db = XMLUtils.createDocumentBuilder(true);
    db.setErrorHandler(new IgnoreAllErrorHandler());
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(input.getBytes())) {
        doc = db.parse(is);
    }
    Canonicalizer c14nizer = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
    // XMLUtils.circumventBug2650(doc);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xPath = xpf.newXPath();
    xPath.setNamespaceContext(new DSNamespaceContext());
    String xpath = "(//*[local-name()='included'] | //@*[parent::node()[local-name()='included']])";
    NodeList nodes = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
    byte[] result = c14nizer.canonicalizeXPathNodeSet(nodes);
    byte[] defined = definedOutput.getBytes();
    assertEquals(definedOutput, new String(result));
    return java.security.MessageDigest.isEqual(defined, result);
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) IgnoreAllErrorHandler(org.apache.xml.security.utils.IgnoreAllErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

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