Java Code Examples for javax.xml.crypto.dsig.dom.DOMValidateContext#setProperty()

The following examples show how to use javax.xml.crypto.dsig.dom.DOMValidateContext#setProperty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ErrorHandlerPermissions.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 2
Source File: ErrorHandlerPermissions.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
    Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE));
    NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
            "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Couldn't find 'Signature' element");
    }
    Element element = (Element) nl.item(0);

    byte[] keyBytes = Base64.getDecoder().decode(validationKey);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
    KeyFactory kf = KeyFactory.getInstance("RSA");
    PublicKey key = kf.generatePublic(spec);
    KeySelector ks = KeySelector.singletonKeySelector(key);

    DOMValidateContext vc = new DOMValidateContext(ks, element);

    // disable secure validation mode
    vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

    // set a dummy dereferencer to be able to get content by references
    vc.setURIDereferencer(dereferencer);

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);

    // run validation
    signature.validate(vc);
}
 
Example 3
Source File: SignatureValidator.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 4
Source File: XMLDSigWithSecMgr.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 5
Source File: XMLDSigWithSecMgr.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 6
Source File: SignatureValidator.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 7
Source File: XMLDSigWithSecMgr.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 8
Source File: SignatureValidator.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 9
Source File: XMLDSigWithSecMgr.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 10
Source File: SignatureValidator.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 11
Source File: TckSigningUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
public static boolean verifySignature(Element element, PublicKey validatingKey) {
    XMLSignatureFactory fac = initXMLSigFactory();
    NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new RuntimeException("Cannot find Signature element");
    }
    DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0));
    try {
        valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
        XMLSignature signature = fac.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        // Check core validation status.
        if (coreValidity == false) {
            System.err.println("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            System.out.println("signature validation status: " + sv);
            // Check the validation status of each Reference.
            @SuppressWarnings("unchecked")
            Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
            System.out.println("---------------------------------------------");
            for (int j = 0; i.hasNext(); j++) {
                Reference ref = (Reference) i.next();
                boolean refValid = ref.validate(valContext);
                System.out.println("ref[" + j + "] validity status: " + refValid);
                System.out.println("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                for (Object xform : ref.getTransforms()) {
                    System.out.println("Transform: " + xform);
                }
                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                String expectedDigValStr = digestToString(ref.getDigestValue());
                System.out.println("    Calc Digest: " + calcDigValStr);
                System.out.println("Expected Digest: " + expectedDigValStr);
                InputStream is = ref.getDigestInputStream();
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line);
                }
                is.close();
                System.out.println("---------------------------------------------");
            }
        } else {
            System.out.println("Signature passed core validation");
        }
        return coreValidity;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 12
Source File: DigSigUtil.java    From juddi with Apache License 2.0 4 votes vote down vote up
private boolean verifySignature(Element element, PublicKey validatingKey, AtomicReference<String> OutReadableErrorMessage) {
        if (OutReadableErrorMessage == null) {
                OutReadableErrorMessage = new AtomicReference<String>();
        }
        XMLSignatureFactory fac = initXMLSigFactory();
        NodeList nl = element.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        if (nl.getLength() == 0) {
                throw new RuntimeException("Cannot find Signature element");
        }
        DOMValidateContext valContext = new DOMValidateContext(validatingKey, nl.item(0));
        try {
                valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
                XMLSignature signature = fac.unmarshalXMLSignature(valContext);
                boolean coreValidity = signature.validate(valContext);
                // Check core validation status.
                if (coreValidity == false) {
                        logger.warn("Signature failed core validation");
                        boolean sv = signature.getSignatureValue().validate(valContext);
                        logger.debug("signature validation status: " + sv);
                        OutReadableErrorMessage.set("signature validation failed: " + sv + "." + OutReadableErrorMessage.get());
                        // Check the validation status of each Reference.
                        @SuppressWarnings("unchecked")
                        Iterator<Reference> i = signature.getSignedInfo().getReferences().iterator();
                        //System.out.println("---------------------------------------------");
                        for (int j = 0; i.hasNext(); j++) {
                                Reference ref = (Reference) i.next();
                                boolean refValid = ref.validate(valContext);
                                logger.debug(j);
                                logger.debug("ref[" + j + "] validity status: " + refValid);
                                if (!refValid) {
                                        OutReadableErrorMessage.set("signature reference " + j + " invalid. " + OutReadableErrorMessage.get());
                                }
                                logger.debug("Ref type: " + ref.getType() + ", URI: " + ref.getURI());
                                for (Object xform : ref.getTransforms()) {
                                        logger.debug("Transform: " + xform);
                                }
                                String calcDigValStr = digestToString(ref.getCalculatedDigestValue());
                                String expectedDigValStr = digestToString(ref.getDigestValue());
                                logger.warn("    Calc Digest: " + calcDigValStr);
                                logger.warn("Expected Digest: " + expectedDigValStr);
                                if (!calcDigValStr.equalsIgnoreCase(expectedDigValStr)) {
                                        OutReadableErrorMessage.set("digest mismatch for signature ref " + j + "." + OutReadableErrorMessage.get());
                                }
                        }
                } else {
                        logger.info("Signature passed core validation");
                }
                return coreValidity;
        } catch (Exception e) {
                OutReadableErrorMessage.set("signature validation failed: " + e.getMessage() + OutReadableErrorMessage.get());
                logger.fatal(e);
                return false;
        }
}
 
Example 13
Source File: SignatureValidator.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 14
Source File: XMLDSigWithSecMgr.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 15
Source File: SignatureValidator.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 16
Source File: XMLDSigWithSecMgr.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    URI policyURI =
        new File(System.getProperty("test.src", "."), "policy").toURI();
    Policy.setPolicy
        (Policy.getInstance("JavaPolicy", new URIParameter(policyURI)));
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 17
Source File: SignatureValidator.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 18
Source File: XMLDSigWithSecMgr.java    From jdk8u_jdk with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}
 
Example 19
Source File: SignatureValidator.java    From TencentKona-8 with GNU General Public License v2.0 4 votes vote down vote up
boolean validate(String fn, KeySelector ks, URIDereferencer ud,
    boolean cache) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document doc = dbf.newDocumentBuilder().parse(new File(dir, fn));
    NodeList nl =
        doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext vc = new DOMValidateContext(ks, sigElement);
    vc.setBaseURI(dir.toURI().toString());
    if (cache) {
        vc.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);
    }
    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    XMLSignature signature = factory.unmarshalXMLSignature(vc);
    if (ud != null) {
        vc.setURIDereferencer(ud);
    }
    boolean coreValidity = signature.validate(vc);

    // Check reference cache
    if (cache) {
        Iterator i = signature.getSignedInfo().getReferences().iterator();
        for (int j=0; i.hasNext(); j++) {
            Reference ref = (Reference) i.next();
            if (!digestInputEqual(ref)) {
                throw new Exception
                    ("cached data for Reference[" + j + "] is not correct");
            }
            // check that dereferenced data does not contain comment nodes
            if (ref.getURI() == "") {
                System.out.println("checking deref data");
                NodeSetData data = (NodeSetData) ref.getDereferencedData();
                Iterator ni = data.iterator();
                while (ni.hasNext()) {
                    Node n = (Node) ni.next();
                    if (n.getNodeType() == Node.COMMENT_NODE) {
                        throw new Exception("dereferenced data for " +
                            " Reference[" + j + " contains comment node");
                    }
                }
            }
        }
    }
    return coreValidity;
}
 
Example 20
Source File: XMLDSigWithSecMgr.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
XMLDSigWithSecMgr() throws Exception {
    setup();
    Document doc = db.newDocument();
    Element envelope = doc.createElementNS
        ("http://example.org/envelope", "Envelope");
    envelope.setAttributeNS("http://www.w3.org/2000/xmlns/",
        "xmlns", "http://example.org/envelope");
    doc.appendChild(envelope);

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    KeyPair kp = kpg.genKeyPair();

    // the policy only grants this test SocketPermission to accept, resolve
    // and connect to localhost so that it can dereference 2nd reference
    System.setProperty("java.security.policy",
            System.getProperty("test.src", ".") + File.separator + "policy");
    System.setSecurityManager(new SecurityManager());

    try {
        // generate a signature with SecurityManager enabled
        ArrayList refs = new ArrayList();
        refs.add(fac.newReference
            ("", sha1,
             Collections.singletonList
                (fac.newTransform(Transform.ENVELOPED,
                 (TransformParameterSpec) null)), null, null));
        refs.add(fac.newReference("http://localhost:" + ss.getLocalPort()
            + "/anything.txt", sha1));
        SignedInfo si = fac.newSignedInfo(withoutComments,
            fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null), refs);
        XMLSignature sig = fac.newXMLSignature(si, null);
        DOMSignContext dsc = new DOMSignContext(kp.getPrivate(), envelope);
        sig.sign(dsc);

        // validate a signature with SecurityManager enabled
        DOMValidateContext dvc = new DOMValidateContext
            (kp.getPublic(), envelope.getFirstChild());

        // disable secure validation mode so that http reference will work
        dvc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);

        sig = fac.unmarshalXMLSignature(dvc);
        if (!sig.validate(dvc)) {
            throw new Exception
                ("XMLDSigWithSecMgr signature validation FAILED");
        }
    } catch (SecurityException se) {
        throw new Exception("XMLDSigWithSecMgr FAILED", se);
    }
    ss.close();
}