Search in sources :

Example 6 with Canonicalizer

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

the class SignedInfo method reparseSignedInfoElem.

private static Element reparseSignedInfoElem(Element element, boolean secureValidation) throws XMLSecurityException {
    /*
         * If a custom canonicalizationMethod is used, canonicalize
         * ds:SignedInfo, reparse it into a new document
         * and replace the original not-canonicalized ds:SignedInfo by
         * the re-parsed canonicalized one.
         */
    Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
    String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
    if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) || c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) {
        // so reparse the SignedInfo to be sure
        try {
            Canonicalizer c14nizer = Canonicalizer.getInstance(c14nMethodURI);
            c14nizer.setSecureValidation(secureValidation);
            byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
            javax.xml.parsers.DocumentBuilder db = XMLUtils.createDocumentBuilder(false, secureValidation);
            try (InputStream is = new ByteArrayInputStream(c14nizedBytes)) {
                Document newdoc = db.parse(is);
                Node imported = element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
                element.getParentNode().replaceChild(imported, element);
                return (Element) imported;
            } finally {
                XMLUtils.repoolDocumentBuilder(db);
            }
        } catch (ParserConfigurationException ex) {
            throw new XMLSecurityException(ex);
        } catch (IOException ex) {
            throw new XMLSecurityException(ex);
        } catch (SAXException ex) {
            throw new XMLSecurityException(ex);
        }
    }
    return element;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) IOException(java.io.IOException) Document(org.w3c.dom.Document) XMLSecurityException(org.apache.xml.security.exceptions.XMLSecurityException) SAXException(org.xml.sax.SAXException) ByteArrayInputStream(java.io.ByteArrayInputStream) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

Example 7 with Canonicalizer

use of org.apache.xml.security.c14n.Canonicalizer in project poi by apache.

the class XAdESXLSignatureFacet method getC14nValue.

public static byte[] getC14nValue(List<Node> nodeList, String c14nAlgoId) {
    ByteArrayOutputStream c14nValue = new ByteArrayOutputStream();
    try {
        for (Node node : nodeList) {
            /*
                 * Re-initialize the c14n else the namespaces will get cached
                 * and will be missing from the c14n resulting nodes.
                 */
            Canonicalizer c14n = Canonicalizer.getInstance(c14nAlgoId);
            c14nValue.write(c14n.canonicalizeSubtree(node));
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException("c14n error: " + e.getMessage(), e);
    }
    return c14nValue.toByteArray();
}
Also used : Node(org.w3c.dom.Node) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer) MarshalException(javax.xml.crypto.MarshalException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) XmlException(org.apache.xmlbeans.XmlException) CRLException(java.security.cert.CRLException) CertificateEncodingException(java.security.cert.CertificateEncodingException)

Example 8 with Canonicalizer

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

the class XMLCipherTest method testSerializedData.

@org.junit.Test
public void testSerializedData() throws Exception {
    if (!haveISOPadding) {
        LOG.warn("Test testSerializedData skipped as necessary algorithms not available");
        return;
    }
    byte[] bits128 = { (byte) 0x10, (byte) 0x11, (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19, (byte) 0x1A, (byte) 0x1B, (byte) 0x1C, (byte) 0x1D, (byte) 0x1E, (byte) 0x1F };
    Key key = new SecretKeySpec(bits128, "AES");
    // source
    Document d = document();
    Element e = (Element) d.getElementsByTagName(element()).item(index());
    // encrypt
    cipher = XMLCipher.getInstance(XMLCipher.AES_128);
    cipher.init(XMLCipher.ENCRYPT_MODE, key);
    // serialize element ...
    Canonicalizer canon = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    canon.setWriter(baos);
    canon.notReset();
    canon.canonicalizeSubtree(e);
    baos.close();
    String before = baos.toString(StandardCharsets.UTF_8.name());
    byte[] serialized = baos.toByteArray();
    EncryptedData encryptedData = null;
    try (InputStream is = new ByteArrayInputStream(serialized)) {
        encryptedData = cipher.encryptData(d, EncryptionConstants.TYPE_ELEMENT, is);
    }
    // decrypt
    XMLCipher dcipher = XMLCipher.getInstance(XMLCipher.AES_128);
    dcipher.init(XMLCipher.DECRYPT_MODE, key);
    String algorithm = encryptedData.getEncryptionMethod().getAlgorithm();
    assertEquals(XMLCipher.AES_128, algorithm);
    byte[] bytes = dcipher.decryptToByteArray(dcipher.martial(encryptedData));
    String after = new String(bytes, StandardCharsets.UTF_8);
    assertEquals(before, after);
    // test with null type
    try (InputStream is = new ByteArrayInputStream(serialized)) {
        encryptedData = cipher.encryptData(d, null, is);
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) SecretKeySpec(javax.crypto.spec.SecretKeySpec) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Element(org.w3c.dom.Element) XMLCipher(org.apache.xml.security.encryption.XMLCipher) ByteArrayOutputStream(java.io.ByteArrayOutputStream) EncryptedData(org.apache.xml.security.encryption.EncryptedData) Document(org.w3c.dom.Document) PublicKey(java.security.PublicKey) EncryptedKey(org.apache.xml.security.encryption.EncryptedKey) Key(java.security.Key) PrivateKey(java.security.PrivateKey) SecretKey(javax.crypto.SecretKey) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

Example 9 with Canonicalizer

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

Example 10 with Canonicalizer

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

the class Canonicalizer20010315Test method testRelativeNSbehaviour.

/**
 * Note: This specification supports the recent XML plenary decision to
 * deprecate relative namespace URIs as follows: implementations of XML
 * canonicalization MUST report an operation failure on documents containing
 * relative namespace URIs. XML canonicalization MUST NOT be implemented
 * with an XML parser that converts relative URIs to absolute URIs.
 *
 * Implementations MUST report an operation failure on documents containing
 * relative namespace URIs.
 *
 * @throws CanonicalizationException
 * @throws FileNotFoundException
 * @throws IOException
 * @throws InvalidCanonicalizerException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
@org.junit.Test
public void testRelativeNSbehaviour() throws IOException, FileNotFoundException, SAXException, ParserConfigurationException, CanonicalizationException, InvalidCanonicalizerException, TransformerException {
    // J-
    String inputStr = "" + "<absolute:correct xmlns:absolute='http://www.absolute.org/#likeVodka'>" + "<relative:incorrect xmlns:relative='../cheating#away'>" + "</relative:incorrect>" + "</absolute:correct>" + "\n" + "";
    // J+
    DocumentBuilder db = XMLUtils.createDocumentBuilder(false);
    Document doc = null;
    try (InputStream is = new ByteArrayInputStream(inputStr.getBytes())) {
        doc = db.parse(is);
    }
    boolean weCatchedTheRelativeNS = false;
    try {
        Canonicalizer c14n = Canonicalizer.getInstance(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS);
        c14n.canonicalizeSubtree(doc);
    } catch (CanonicalizationException cex) {
        // if we reach this point - good.
        LOG.debug("We catched the C14nEx, that's good: " + cex.getMessage());
        weCatchedTheRelativeNS = true;
    }
    assertTrue("We did not catch the relative namespace", weCatchedTheRelativeNS);
}
Also used : DocumentBuilder(javax.xml.parsers.DocumentBuilder) ByteArrayInputStream(java.io.ByteArrayInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) CanonicalizationException(org.apache.xml.security.c14n.CanonicalizationException) Document(org.w3c.dom.Document) Canonicalizer(org.apache.xml.security.c14n.Canonicalizer)

Aggregations

Canonicalizer (org.apache.xml.security.c14n.Canonicalizer)14 ByteArrayInputStream (java.io.ByteArrayInputStream)8 Document (org.w3c.dom.Document)8 InputStream (java.io.InputStream)7 DocumentBuilder (javax.xml.parsers.DocumentBuilder)7 XPath (javax.xml.xpath.XPath)5 XPathFactory (javax.xml.xpath.XPathFactory)5 DSNamespaceContext (org.apache.xml.security.test.dom.DSNamespaceContext)5 IOException (java.io.IOException)4 NodeList (org.w3c.dom.NodeList)4 ByteArrayOutputStream (java.io.ByteArrayOutputStream)3 IgnoreAllErrorHandler (org.apache.xml.security.utils.IgnoreAllErrorHandler)3 Node (org.w3c.dom.Node)3 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 TestVectorResolver (org.apache.xml.security.test.dom.resource.TestVectorResolver)2 Element (org.w3c.dom.Element)2 SystemConfigurationException (com.sun.identity.common.SystemConfigurationException)1 SessionException (com.sun.identity.plugin.session.SessionException)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1