Search in sources :

Example 21 with DSNamespaceContext

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

the class AbstractSignatureVerificationTest method signUsingDOM.

/**
 * Sign the document using DOM
 */
protected XMLSignature signUsingDOM(String algorithm, Document document, List<String> localNames, Key signingKey, String c14nMethod, String digestMethod, List<ReferenceInfo> additionalReferences, String referenceC14NMethod, ResourceResolverSpi resourceResolverSpi) throws Exception {
    XMLSignature sig = new XMLSignature(document, "", algorithm, c14nMethod);
    if (resourceResolverSpi != null) {
        sig.addResourceResolver(resourceResolverSpi);
    }
    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(referenceC14NMethod);
            sig.addDocument("#" + id, transforms, digestMethod);
        }
    }
    if (additionalReferences != null) {
        for (int i = 0; i < additionalReferences.size(); i++) {
            ReferenceInfo referenceInfo = additionalReferences.get(i);
            if (referenceInfo.isBinary()) {
                sig.addDocument(referenceInfo.getResource(), null, referenceInfo.getDigestMethod());
            } else {
                Transforms transforms = new Transforms(document);
                for (int j = 0; j < referenceInfo.getC14NMethod().length; j++) {
                    String transform = referenceInfo.getC14NMethod()[j];
                    transforms.addTransform(transform);
                }
                sig.addDocument(referenceInfo.getResource(), transforms, referenceInfo.getDigestMethod());
            }
        }
    }
    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 22 with DSNamespaceContext

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

the class KeyWrapEncryptionVerificationTest method encrypt.

private void encrypt(EncryptedKey encryptedKey, String algorithm, Document document, List<String> localNames, Key encryptingKey) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.ENCRYPT_MODE, encryptingKey);
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    EncryptedData builder = cipher.getEncryptedData();
    KeyInfo builderKeyInfo = builder.getKeyInfo();
    if (builderKeyInfo == null) {
        builderKeyInfo = new KeyInfo(document);
        builder.setKeyInfo(builderKeyInfo);
    }
    builderKeyInfo.add(encryptedKey);
    for (String localName : localNames) {
        String expression = "//*[local-name()='" + localName + "']";
        Element elementToEncrypt = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
        Assert.assertNotNull(elementToEncrypt);
        document = cipher.doFinal(document, elementToEncrypt, false);
    }
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    Assert.assertTrue(nodeList.getLength() > 0);
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) KeyInfo(org.apache.xml.security.keys.KeyInfo) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData)

Example 23 with DSNamespaceContext

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

the class SymmetricEncryptionVerificationTest method encryptUsingDOM.

/**
 * Encrypt the document using DOM APIs and run some tests on the encrypted Document.
 */
private void encryptUsingDOM(String algorithm, SecretKey secretKey, String keyTransportAlgorithm, Key wrappingKey, boolean includeWrappingKeyInfo, Document document, List<String> localNames, boolean content) throws Exception {
    XMLCipher cipher = XMLCipher.getInstance(algorithm);
    cipher.init(XMLCipher.ENCRYPT_MODE, secretKey);
    if (wrappingKey != null) {
        XMLCipher newCipher = XMLCipher.getInstance(keyTransportAlgorithm);
        newCipher.init(XMLCipher.WRAP_MODE, wrappingKey);
        EncryptedKey encryptedKey = newCipher.encryptKey(document, secretKey);
        if (includeWrappingKeyInfo && wrappingKey instanceof PublicKey) {
            // Create a KeyInfo for the EncryptedKey
            KeyInfo encryptedKeyKeyInfo = encryptedKey.getKeyInfo();
            if (encryptedKeyKeyInfo == null) {
                encryptedKeyKeyInfo = new KeyInfo(document);
                encryptedKeyKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
                encryptedKey.setKeyInfo(encryptedKeyKeyInfo);
            }
            encryptedKeyKeyInfo.add((PublicKey) wrappingKey);
        }
        EncryptedData builder = cipher.getEncryptedData();
        KeyInfo builderKeyInfo = builder.getKeyInfo();
        if (builderKeyInfo == null) {
            builderKeyInfo = new KeyInfo(document);
            builderKeyInfo.getElement().setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:dsig", "http://www.w3.org/2000/09/xmldsig#");
            builder.setKeyInfo(builderKeyInfo);
        }
        builderKeyInfo.add(encryptedKey);
    }
    XPathFactory xpf = XPathFactory.newInstance();
    XPath xpath = xpf.newXPath();
    xpath.setNamespaceContext(new DSNamespaceContext());
    for (String localName : localNames) {
        String expression = "//*[local-name()='" + localName + "']";
        Element elementToEncrypt = (Element) xpath.evaluate(expression, document, XPathConstants.NODE);
        Assert.assertNotNull(elementToEncrypt);
        document = cipher.doFinal(document, elementToEncrypt, content);
    }
    NodeList nodeList = document.getElementsByTagNameNS(XMLSecurityConstants.TAG_xenc_EncryptedData.getNamespaceURI(), XMLSecurityConstants.TAG_xenc_EncryptedData.getLocalPart());
    Assert.assertTrue(nodeList.getLength() > 0);
}
Also used : XPath(javax.xml.xpath.XPath) XPathFactory(javax.xml.xpath.XPathFactory) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) KeyInfo(org.apache.xml.security.keys.KeyInfo) PublicKey(java.security.PublicKey) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) XMLCipher(org.apache.xml.security.encryption.XMLCipher) EncryptedData(org.apache.xml.security.encryption.EncryptedData)

Example 24 with DSNamespaceContext

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

the class InteropTestBase method verify.

public boolean verify(String filename, ResourceResolverSpi resolver, boolean followManifests, boolean secureValidation) throws Exception {
    File f = new File(filename);
    javax.xml.parsers.DocumentBuilder db = XMLUtils.createDocumentBuilder(false, false);
    org.w3c.dom.Document doc = db.parse(f);
    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, f.toURI().toURL().toString(), secureValidation);
    if (resolver != null) {
        signature.addResourceResolver(resolver);
    }
    signature.setFollowNestedManifests(followManifests);
    KeyInfo ki = signature.getKeyInfo();
    boolean result = false;
    if (ki != null) {
        X509Certificate cert = ki.getX509Certificate();
        if (cert != null) {
            result = signature.checkSignatureValue(cert);
        } else {
            PublicKey pk = ki.getPublicKey();
            if (pk != null) {
                result = signature.checkSignatureValue(pk);
            } else {
                throw new RuntimeException("Did not find a public key, so I can't check the signature");
            }
        }
        checkReferences(signature);
    } else {
        throw new RuntimeException("Did not find a KeyInfo");
    }
    if (!result) {
        for (int i = 0; i < signature.getSignedInfo().getLength(); i++) {
            boolean refVerify = signature.getSignedInfo().getVerificationResult(i);
            if (refVerify) {
                LOG.debug("Reference " + i + " was OK");
            } else {
                // JavaUtils.writeBytesToFilename(filename + i + ".apache.txt", signature.getSignedInfo().item(i).getContentsAfterTransformation().getBytes());
                LOG.debug("Reference " + i + " was not OK");
            }
        }
        checkReferences(signature);
    // throw new RuntimeException("Falle:"+sb.toString());
    }
    return result;
}
Also used : XPath(javax.xml.xpath.XPath) PublicKey(java.security.PublicKey) 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) File(java.io.File)

Example 25 with DSNamespaceContext

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

the class Canonicalizer11Test method c14nAndCompare.

private boolean c14nAndCompare(String fileIn, String fileRef, String fileOut, String c14nURI, boolean validating, String xpath, Map<String, String> namespaces) throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException, XPathExpressionException {
    DocumentBuilder documentBuilder = XMLUtils.createDocumentBuilder(validating, false);
    // throw away all warnings and errors
    documentBuilder.setErrorHandler(new IgnoreAllErrorHandler());
    // org.xml.sax.EntityResolver resolver = new TestVectorResolver();
    // documentBuilder.setEntityResolver(resolver);
    // Document doc = documentBuilder.parse(resolver.resolveEntity(null, fileIn));
    Document doc = documentBuilder.parse(fileIn);
    Canonicalizer c14n = Canonicalizer.getInstance(c14nURI);
    byte[] c14nBytes = null;
    if (xpath == null) {
        c14nBytes = c14n.canonicalizeSubtree(doc);
    } else {
        NodeList nl = null;
        XPathFactory xpf = XPathFactory.newInstance();
        XPath xPath = xpf.newXPath();
        DSNamespaceContext namespaceContext = new DSNamespaceContext(namespaces);
        xPath.setNamespaceContext(namespaceContext);
        nl = (NodeList) xPath.evaluate(xpath, doc, XPathConstants.NODESET);
        c14nBytes = c14n.canonicalizeXPathNodeSet(nl);
    }
    // org.xml.sax.InputSource refIs = resolver.resolveEntity(null, fileRef);
    // byte refBytes[] = JavaUtils.getBytesFromStream(refIs.getByteStream());
    byte[] refBytes = JavaUtils.getBytesFromFile(fileRef);
    // if everything is OK, result is true; we do a binary compare, byte by byte
    boolean result = java.security.MessageDigest.isEqual(refBytes, c14nBytes);
    if (!result) {
        File f = new File(fileOut);
        if (!f.exists()) {
            File parent = new File(f.getParent());
            parent.mkdirs();
            f.createNewFile();
        }
        FileOutputStream fos = new FileOutputStream(f);
        fos.write(c14nBytes);
        LOG.debug("Wrote erroneous result to file " + f.toURI().toURL().toString());
        assertEquals(new String(refBytes), new String(c14nBytes));
        fos.close();
    }
    return result;
}
Also used : XPath(javax.xml.xpath.XPath) IgnoreAllErrorHandler(org.apache.xml.security.utils.IgnoreAllErrorHandler) NodeList(org.w3c.dom.NodeList) Document(org.w3c.dom.Document) XPathFactory(javax.xml.xpath.XPathFactory) DocumentBuilder(javax.xml.parsers.DocumentBuilder) DSNamespaceContext(org.apache.xml.security.test.dom.DSNamespaceContext) FileOutputStream(java.io.FileOutputStream) File(java.io.File) 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