Search in sources :

Example 11 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_sign_spec.

static void test_create_sign_spec() throws Exception {
    System.out.println("* Generating sign-spec.xml");
    List<Reference> refs = new ArrayList<Reference>(2);
    // create reference 1
    List<XPathType> types = new ArrayList<XPathType>(3);
    types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));
    types.add(new XPathType(" //NotToBeSigned ", XPathType.Filter.SUBTRACT));
    types.add(new XPathType(" //ReallyToBeSigned ", XPathType.Filter.UNION));
    XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
    refs.add(fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)), null, null));
    // create reference 2
    List<Transform> trans2 = new ArrayList<Transform>(2);
    trans2.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType(" / ", XPathType.Filter.UNION)));
    trans2.add(fac.newTransform(Transform.XPATH2, xp2));
    refs.add(fac.newReference("#signature-value", fac.newDigestMethod(DigestMethod.SHA1, null), trans2, null, null));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
    // create KeyInfo
    List<XMLStructure> kits = new ArrayList<XMLStructure>(2);
    kits.add(kifac.newKeyValue(validatingKey));
    List<Object> xds = new ArrayList<Object>(2);
    xds.add("CN=User");
    xds.add(signingCert);
    kits.add(kifac.newX509Data(xds));
    KeyInfo ki = kifac.newKeyInfo(kits);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, null, null, "signature-value");
    Document doc = db.newDocument();
    Element tbs1 = doc.createElementNS(null, "ToBeSigned");
    Comment tbs1Com = doc.createComment(" comment ");
    Element tbs1Data = doc.createElementNS(null, "Data");
    Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");
    Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");
    Comment tbs1rtbsCom = doc.createComment(" comment ");
    Element tbs1rtbsData = doc.createElementNS(null, "Data");
    tbs1rtbs.appendChild(tbs1rtbsCom);
    tbs1rtbs.appendChild(tbs1rtbsData);
    tbs1ntbs.appendChild(tbs1rtbs);
    tbs1.appendChild(tbs1Com);
    tbs1.appendChild(tbs1Data);
    tbs1.appendChild(tbs1ntbs);
    Element tbs2 = doc.createElementNS(null, "ToBeSigned");
    Element tbs2Data = doc.createElementNS(null, "Data");
    Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");
    Element tbs2ntbsData = doc.createElementNS(null, "Data");
    tbs2ntbs.appendChild(tbs2ntbsData);
    tbs2.appendChild(tbs2Data);
    tbs2.appendChild(tbs2ntbs);
    Element document = doc.createElementNS(null, "Document");
    document.appendChild(tbs1);
    document.appendChild(tbs2);
    doc.appendChild(document);
    DOMSignContext dsc = new DOMSignContext(signingKey, document);
    sig.sign(dsc);
    //      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
    DOMValidateContext dvc = new DOMValidateContext(new KeySelectors.KeyValueKeySelector(), document.getLastChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : XMLStructure(javax.xml.crypto.XMLStructure) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReference(javax.xml.crypto.URIReference) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext)

Example 12 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class SignatureValidator method validate.

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;
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext)

Example 13 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_exc_signature.

static void test_create_exc_signature() throws Exception {
    System.out.println("* Generating exc_signature.xml");
    List<Reference> refs = new ArrayList<Reference>(4);
    // create reference 1
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null));
    // create reference 2
    List<String> prefixList = new ArrayList<String>(2);
    prefixList.add("bar");
    prefixList.add("#default");
    ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)), null, null));
    // create reference 3
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null)), null, null));
    // create reference 4
    prefixList = new ArrayList<String>(2);
    prefixList.add("bar");
    prefixList.add("#default");
    params = new ExcC14NParameterSpec(prefixList);
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)), null, null));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
    // create KeyInfo
    List<XMLStructure> kits = new ArrayList<XMLStructure>(2);
    kits.add(kifac.newKeyValue(validatingKey));
    KeyInfo ki = kifac.newKeyInfo(kits);
    // create Objects
    Document doc = db.newDocument();
    Element baz = doc.createElementNS("urn:bar", "bar:Baz");
    Comment com = doc.createComment(" comment ");
    baz.appendChild(com);
    XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(baz)), "to-be-signed", null, null);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);
    Element foo = doc.createElementNS("urn:foo", "Foo");
    foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
    foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
    doc.appendChild(foo);
    DOMSignContext dsc = new DOMSignContext(signingKey, foo);
    dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");
    sig.sign(dsc);
    //      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
    DOMValidateContext dvc = new DOMValidateContext(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : URIReference(javax.xml.crypto.URIReference) XMLStructure(javax.xml.crypto.XMLStructure) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext)

Example 14 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature_external.

private static void test_create_signature_external(SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks, boolean b64) throws Exception {
    // create reference
    Reference ref;
    if (b64) {
        ref = fac.newReference(STYLESHEET_B64, sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null);
    } else {
        ref = fac.newReference(STYLESHEET, sha1);
    }
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref));
    Document doc = db.newDocument();
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki);
    DOMSignContext dsc = new DOMSignContext(signingKey, doc);
    dsc.setURIDereferencer(httpUd);
    sig.sign(dsc);
    DOMValidateContext dvc = new DOMValidateContext(ks, doc.getDocumentElement());
    File f = new File(DATA_DIR);
    dvc.setBaseURI(f.toURI().toString());
    dvc.setURIDereferencer(httpUd);
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
}
Also used : URIReference(javax.xml.crypto.URIReference) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 15 with DOMValidateContext

use of javax.xml.crypto.dsig.dom.DOMValidateContext in project simba-os by cegeka.

the class Utils method validateSign.

/**
     * Validate signature (Message or Assertion).
     *
     * @param signatureElement The element we should validate
     * @param cert             The pubic cert
     * @param fingerprint      The fingerprint of the public cert
     * @return True if the sign is valid, false otherwise.
     */
public static boolean validateSign(Node signatureElement, Certificate cert, String... fingerprint) throws Exception {
    boolean res;
    DOMValidateContext ctx = new DOMValidateContext(cert.getPublicKey(), signatureElement);
    XMLSignatureFactory sigF = XMLSignatureFactory.getInstance("DOM");
    try {
        XMLSignature xmlSignature = sigF.unmarshalXMLSignature(ctx);
        res = xmlSignature.validate(ctx);
    } catch (MarshalException e) {
        log.error("Cannot locate Signature Node " + e.getMessage(), e);
        throw e;
    } catch (NullPointerException e) {
        log.error("Context can't be validated", e);
        throw e;
    }
    return res;
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) MarshalException(javax.xml.crypto.MarshalException) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext)

Aggregations

DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)15 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 URIReferenceException (javax.xml.crypto.URIReferenceException)8 URIReference (javax.xml.crypto.URIReference)7 XMLStructure (javax.xml.crypto.XMLStructure)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)4 NodeList (org.w3c.dom.NodeList)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)3 Key (java.security.Key)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 X509Certificate (java.security.cert.X509Certificate)2 SecretKey (javax.crypto.SecretKey)2 KeySelector (javax.xml.crypto.KeySelector)2 Document (org.w3c.dom.Document)2 Element (org.w3c.dom.Element)2 IOException (java.io.IOException)1 BigInteger (java.math.BigInteger)1 KeyPair (java.security.KeyPair)1