API Overview API Index Package Overview Direct link to this page
JDK 1.6
  org.jcp.xml.dsig.internal.dom. DOMReference View Javadoc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488

/*
 * Portions copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */
/*
 * =========================================================================== 
 *
 * (C) Copyright IBM Corp. 2003 All Rights Reserved.
 *
 * ===========================================================================
 */
/*
 * $Id: DOMReference.java,v 1.40 2005/09/19 18:27:04 mullan Exp $
 */
package org.jcp.xml.dsig.internal.dom;

import javax.xml.crypto.*;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dom.DOMCryptoContext;
import javax.xml.crypto.dom.DOMURIReference;

import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;

import org.jcp.xml.dsig.internal.DigesterOutputStream;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;

/**
 * DOM-based implementation of Reference.
 *
 * @author Sean Mullan
 * @author Joyce Leung
 */
public final class DOMReference extends DOMStructure 
    implements Reference, DOMURIReference {

    private static Logger log = Logger.getLogger("org.jcp.xml.dsig.internal.dom");

    private final DigestMethod digestMethod;
    private final String id;
    private final List appliedTransforms;
    private final List transforms;
    private final List allTransforms;
    private final Data appliedTransformData;
    private Attr here;
    private final String uri;
    private final String type;
    private byte[] digestValue;
    private byte[] calcDigestValue;
    private Element refElem;
    private boolean digested = false;
    private boolean validated = false;
    private boolean validationStatus;
    private Data derefData;
    private InputStream dis;
    private MessageDigest md;

    /**
     * Creates a <code>Reference</code> from the specified parameters.
     *
     * @param uri the URI (may be null)
     * @param type the type (may be null)
     * @param dm the digest method
     * @param transforms a list of {@link Transform}s. The list
     *    is defensively copied to protect against subsequent modification.
     *    May be <code>null</code> or empty.
     * @param id the reference ID (may be <code>null</code>)
     * @return a <code>Reference</code>
     * @throws NullPointerException if <code>dm</code> is <code>null</code>
     * @throws ClassCastException if any of the <code>transforms</code> are
     *    not of type <code>Transform</code>
     */
    public DOMReference(String uri, String type, DigestMethod dm, 
	List transforms, String id) {
	this(uri, type, dm, null, null, transforms, id, null);
    }

    public DOMReference(String uri, String type, DigestMethod dm, 
	List appliedTransforms, Data result, List transforms, String id) {
	this(uri, type, dm, appliedTransforms, result, transforms, id, null);
    }

    public DOMReference(String uri, String type, DigestMethod dm, 
	List appliedTransforms, Data result, List transforms, String id, 
	byte[] digestValue){
	if (dm == null) {
	    throw new NullPointerException("DigestMethod must be non-null");
	}
        if (appliedTransforms == null || appliedTransforms.isEmpty()) {
            this.appliedTransforms = Collections.EMPTY_LIST;
        } else {
            List transformsCopy = new ArrayList(appliedTransforms);
            for (int i = 0, size = transformsCopy.size(); i < size; i++) {
                if (!(transformsCopy.get(i) instanceof Transform)) {
                    throw new ClassCastException
                        ("appliedTransforms["+i+"] is not a valid type");
                }
            }
            this.appliedTransforms = 
		Collections.unmodifiableList(transformsCopy);
        }
        if (transforms == null || transforms.isEmpty()) {
            this.transforms = Collections.EMPTY_LIST;
        } else {
            List transformsCopy = new ArrayList(transforms);
            for (int i = 0, size = transformsCopy.size(); i < size; i++) {
                if (!(transformsCopy.get(i) instanceof Transform)) {
                    throw new ClassCastException
                        ("transforms["+i+"] is not a valid type");
                }
            }
            this.transforms = Collections.unmodifiableList(transformsCopy);
        }
	List all = new ArrayList(this.appliedTransforms);
	all.addAll(this.transforms);
	this.allTransforms = Collections.unmodifiableList(all);
	this.digestMethod = dm;
	this.uri = uri;
        if ((uri != null) && (!uri.equals(""))) {
            try {
                new URI(uri);
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException(e.getMessage());
            }
        }
	this.type = type;
	this.id = id;
	if (digestValue != null) {
	    this.digestValue = (byte[]) digestValue.clone();
	    this.digested = true;
	}
	this.appliedTransformData = result;
    }
 
    /**
     * Creates a <code>DOMReference</code> from an element.
     *
     * @param refElem a Reference element
     */
    public DOMReference(Element refElem, XMLCryptoContext context) 
	throws MarshalException {
        // unmarshal Transforms, if specified
        Element nextSibling = DOMUtils.getFirstChildElement(refElem);
        List transforms = new ArrayList(5);
        if (nextSibling.getLocalName().equals("Transforms")) {
	    Element transformElem = DOMUtils.getFirstChildElement(nextSibling);
	    while (transformElem != null) {
                transforms.add(new DOMTransform(transformElem, context));
	        transformElem = DOMUtils.getNextSiblingElement(transformElem);
	    }
            nextSibling = DOMUtils.getNextSiblingElement(nextSibling);
	}

        // unmarshal DigestMethod
        Element dmElem = nextSibling;
        this.digestMethod = DOMDigestMethod.unmarshal(dmElem);

        // unmarshal DigestValue
	try {
	    Element dvElem = DOMUtils.getNextSiblingElement(dmElem);
	    this.digestValue = Base64.decode(dvElem);
	} catch (Base64DecodingException bde) {
	    throw new MarshalException(bde);
	}

	// unmarshal attributes
        this.uri = DOMUtils.getAttributeValue(refElem, "URI");
        this.id = DOMUtils.getAttributeValue(refElem, "Id");

        this.type = DOMUtils.getAttributeValue(refElem, "Type");
	this.here = refElem.getAttributeNodeNS(null, "URI");
	this.refElem = refElem;

        if (transforms.isEmpty()) {
            this.transforms = Collections.EMPTY_LIST;
        } else {
            this.transforms = Collections.unmodifiableList(transforms);
        }
	this.appliedTransforms = Collections.EMPTY_LIST;
	this.allTransforms = transforms;
	this.appliedTransformData = null;
    }

    public DigestMethod getDigestMethod() {
	return digestMethod;
    }

    public String getId() {
	return id;
    }

    public String getURI() {
	return uri;
    }

    public String getType() {
	return type;
    }

    public List getTransforms() {
	return allTransforms;
    }

    public byte[] getDigestValue() {
	return (digestValue == null ? null : (byte[]) digestValue.clone());
    }

    public byte[] getCalculatedDigestValue() {
	return (calcDigestValue == null ? null 
		: (byte[]) calcDigestValue.clone());
    }

    public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
	throws MarshalException {
	if (log.isLoggable(Level.FINE)) {
            log.log(Level.FINE, "Marshalling Reference");
	}
        Document ownerDoc = DOMUtils.getOwnerDocument(parent);

        refElem = DOMUtils.createElement
            (ownerDoc, "Reference", XMLSignature.XMLNS, dsPrefix);

	// set attributes
	DOMUtils.setAttributeID(refElem, "Id", id);
        DOMUtils.setAttribute(refElem, "URI", uri);
        DOMUtils.setAttribute(refElem, "Type", type);

	// create and append Transforms element
	if (!transforms.isEmpty() || !appliedTransforms.isEmpty()) {
            Element transformsElem = DOMUtils.createElement
		(ownerDoc, "Transforms", XMLSignature.XMLNS, dsPrefix);
	    refElem.appendChild(transformsElem);
	    for (int i = 0, size = appliedTransforms.size(); i < size; i++) {
	        DOMStructure transform = 
		    (DOMStructure) appliedTransforms.get(i);
	        transform.marshal(transformsElem, dsPrefix, context);
	    }
	    for (int i = 0, size = transforms.size(); i < size; i++) {
	        DOMStructure transform = (DOMStructure) transforms.get(i);
	        transform.marshal(transformsElem, dsPrefix, context);
	    }
	}

	// create and append DigestMethod element
	((DOMDigestMethod) digestMethod).marshal(refElem, dsPrefix, context);

	// create and append DigestValue element
	if (log.isLoggable(Level.FINE)) {
	    log.log(Level.FINE, "Adding digestValueElem");
	}
        Element digestValueElem = DOMUtils.createElement
            (ownerDoc, "DigestValue", XMLSignature.XMLNS, dsPrefix);
	if (digestValue != null) {
            digestValueElem.appendChild
	        (ownerDoc.createTextNode(Base64.encode(digestValue)));
	}
        refElem.appendChild(digestValueElem);

	parent.appendChild(refElem);
	here = refElem.getAttributeNodeNS(null, "URI");
    }

    public void digest(XMLSignContext signContext) 
	throws XMLSignatureException {
	Data data = null;
	if (appliedTransformData == null) {
	    data = dereference(signContext);
	} else {
	    data = appliedTransformData;
	}
	digestValue = transform(data, signContext);

	// insert digestValue into DigestValue element
	String encodedDV = Base64.encode(digestValue);
	if (log.isLoggable(Level.FINE)) {
	    log.log(Level.FINE, "Reference object uri = " + uri);
	}
        Element digestElem = DOMUtils.getLastChildElement(refElem);
	if (digestElem == null) {
	    throw new XMLSignatureException("DigestValue element expected");
	}
	DOMUtils.removeAllChildren(digestElem);
	digestElem.appendChild
	    (refElem.getOwnerDocument().createTextNode(encodedDV));

	digested = true;
	if (log.isLoggable(Level.FINE)) {
	    log.log(Level.FINE, "Reference digesting completed");
	}
    }

    public boolean validate(XMLValidateContext validateContext)
        throws XMLSignatureException {
	if (validateContext == null) {
	    throw new NullPointerException("validateContext cannot be null");
	}
	if (validated) {
	    return validationStatus;
	}
	Data data = dereference(validateContext);
	calcDigestValue = transform(data, validateContext);

	if (log.isLoggable(Level.FINE)) {
	    log.log(Level.FINE, "Expected digest: " 
		+ Base64.encode(digestValue));
	    log.log(Level.FINE, "Actual digest: " 
		+ Base64.encode(calcDigestValue));
	}

	validationStatus = Arrays.equals(digestValue, calcDigestValue);
	validated = true;
	return validationStatus;
    }

    public Data getDereferencedData() {
	return derefData;
    }

    public InputStream getDigestInputStream() {
	return dis;
    }

    private Data dereference(XMLCryptoContext context) 
	throws XMLSignatureException {
        Data data = null;

	// use user-specified URIDereferencer if specified; otherwise use deflt
	URIDereferencer deref = context.getURIDereferencer();
	if (deref == null) {
	    deref = DOMURIDereferencer.INSTANCE;
	}
	try {
            data = deref.dereference(this, context);
	    if (log.isLoggable(Level.FINE)) {
                log.log(Level.FINE, "URIDereferencer class name: " 
	            + deref.getClass().getName());
                log.log(Level.FINE, "Data class name: " 
		    + data.getClass().getName());
	    }
        } catch (URIReferenceException ure) {
	    throw new XMLSignatureException(ure);
        }

	return data;
    }

    private byte[] transform(Data dereferencedData, 
	XMLCryptoContext context) throws XMLSignatureException {

	if (md == null) {
	    try {
		md = MessageDigest.getInstance
                    (((DOMDigestMethod) digestMethod).getMessageDigestAlgorithm());
	    } catch (NoSuchAlgorithmException nsae) {
	        throw new XMLSignatureException(nsae);
	    }
	}
	md.reset();
	DigesterOutputStream dos;
        Boolean cache = (Boolean)
            context.getProperty("javax.xml.crypto.dsig.cacheReference");
        if (cache != null && cache.booleanValue() == true) {
            this.derefData = copyDerefData(dereferencedData);
            dos = new DigesterOutputStream(md, true);
        } else {
            dos = new DigesterOutputStream(md);
        }
	OutputStream os = new UnsyncBufferedOutputStream(dos);
	Data data = dereferencedData;
	for (int i = 0, size = transforms.size(); i < size; i++) {
	    DOMTransform transform = (DOMTransform) transforms.get(i);
	    try {
                if (i < size - 1) {
                    data = transform.transform(data, context);
                } else {
                    data = transform.transform(data, context, os);
                }
	    } catch (TransformException te) {
		throw new XMLSignatureException(te);
	    }
        }
	
	try {
	    if (data != null) {
	        XMLSignatureInput xi;
	        if (data instanceof ApacheData) {
	            xi = ((ApacheData) data).getXMLSignatureInput();
	        } else if (data instanceof OctetStreamData) {
	            xi = new XMLSignatureInput
			(((OctetStreamData)data).getOctetStream());
	        } else if (data instanceof NodeSetData) {
		    TransformService spi = TransformService.getInstance
		        (CanonicalizationMethod.INCLUSIVE, "DOM");
                    data = spi.transform(data, context);
	            xi = new XMLSignatureInput
		        (((OctetStreamData)data).getOctetStream());
	        } else {
	            throw new XMLSignatureException("unrecognized Data type");
	        }
	        xi.updateOutputStream(os);
	    }
	    os.flush();
            if (cache != null && cache.booleanValue() == true) {
                this.dis = dos.getInputStream();
            }
	    return dos.getDigestValue();
	} catch (Exception e) {
	    throw new XMLSignatureException(e);
	}
    }

    public Node getHere() {
	return here;
    }

    public boolean equals(Object o) {
	if (this == o) {
            return true;
	}

        if (!(o instanceof Reference)) {
            return false;
	}
        Reference oref = (Reference) o;

	boolean idsEqual = (id == null ? oref.getId() == null :
	    id.equals(oref.getId()));
	boolean urisEqual = (uri == null ? oref.getURI() == null :
	    uri.equals(oref.getURI()));
	boolean typesEqual = (type == null ? oref.getType() == null :
	    type.equals(oref.getType()));
	boolean digestValuesEqual = 
	    Arrays.equals(digestValue, oref.getDigestValue());

	return (digestMethod.equals(oref.getDigestMethod()) && idsEqual &&
	    urisEqual && typesEqual && transforms.equals(oref.getTransforms()));
    }

    boolean isDigested() {
	return digested;
    }

    private static Data copyDerefData(Data dereferencedData) {
        if (dereferencedData instanceof ApacheData) {
            // need to make a copy of the Data
            ApacheData ad = (ApacheData) dereferencedData;
            XMLSignatureInput xsi = ad.getXMLSignatureInput();
            if (xsi.isNodeSet()) {
                try {
                    final Set s = xsi.getNodeSet();
                    return new NodeSetData() {
                        public Iterator iterator() { return s.iterator(); }
                    };
                } catch (Exception e) {
                    // log a warning
                    log.log(Level.WARNING,
                        "cannot cache dereferenced data: " + e);
                    return null;
                }
            } else if (xsi.isElement()) {
                return new DOMSubTreeData
                    (xsi.getSubNode(), xsi.isExcludeComments());
            } else if (xsi.isOctetStream() || xsi.isByteArray()) {
                try {
                return new OctetStreamData
                  (xsi.getOctetStream(), xsi.getSourceURI(), xsi.getMIMEType());
                } catch (IOException ioe) {
                    // log a warning
                    log.log(Level.WARNING,
                        "cannot cache dereferenced data: " + ioe);
                    return null;
                }
            }
        }
        return dereferencedData;
    }
}

Generated By: JavaOnTracks Doclet 0.1.4     ©Thibaut Colar