Example usage for javax.xml.crypto URIDereferencer URIDereferencer

List of usage examples for javax.xml.crypto URIDereferencer URIDereferencer

Introduction

In this page you can find the example usage for javax.xml.crypto URIDereferencer URIDereferencer.

Prototype

URIDereferencer

Source Link

Usage

From source file:no.difi.sdp.client.asice.signature.CreateSignatureTest.java

private boolean verify_signature(final Signature signature2) {
    try {//ww w  .  j  av a  2 s  .  c o  m
        signature2.getBytes();
        DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
        fac.setNamespaceAware(true);
        DocumentBuilder builder = fac.newDocumentBuilder();
        final Document doc = builder.parse(new ByteArrayInputStream(signature2.getBytes()));
        //System.err.println(new String(signature2.getBytes()));
        NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
        DOMValidateContext valContext = new DOMValidateContext(
                noekkelpar.getSertifikat().getX509Certificate().getPublicKey(), nl.item(0));
        valContext.setURIDereferencer(new URIDereferencer() {
            @Override
            public Data dereference(final URIReference uriReference, final XMLCryptoContext context)
                    throws URIReferenceException {
                //System.out.println("$$$$ " + uriReference.getURI());
                for (AsicEAttachable file : files) {
                    if (file.getFileName().equals(uriReference.getURI().toString())) {
                        return new OctetStreamData(new ByteArrayInputStream(file.getBytes()));
                    }
                }
                uriReference.getURI().toString().replace("#", "");
                Node element = doc.getElementsByTagName("SignedProperties").item(0);
                return new DOMSubTreeData(element, false);

            }
        });
        XMLSignatureFactory fact = XMLSignatureFactory.getInstance("DOM");
        XMLSignature signature = fact.unmarshalXMLSignature(valContext);
        boolean coreValidity = signature.validate(valContext);
        if (coreValidity == false) {
            System.err.println("Signature failed core validation");
            boolean sv = signature.getSignatureValue().validate(valContext);
            System.out.println("signature validation status: " + sv);
            if (sv == false) {
                // Check the validation status of each Reference.
                Iterator i = signature.getSignedInfo().getReferences().iterator();
                for (int j = 0; i.hasNext(); j++) {
                    boolean refValid = ((javax.xml.crypto.dsig.Reference) i.next()).validate(valContext);
                    System.out.println("ref[" + j + "] validity status: " + refValid);
                }
            }
        }
        return coreValidity;
    } catch (Exception ex) {
        ex.printStackTrace(System.err);
        return false;
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloped(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, JAXBException, MarshalException, XMLSignatureException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override//from   w  w  w. j  a  va2  s .co m
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

    List<Reference> references = new ArrayList<Reference>();

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

    List<XMLObject> objects = new ArrayList<XMLObject>();

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}