KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > org > apache > xml > internal > security > signature > Reference


1
2 /*
3  * Copyright 1999-2004 The Apache Software Foundation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  * http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  */

18 package com.sun.org.apache.xml.internal.security.signature;
19
20
21
22 import java.io.IOException JavaDoc;
23 import java.io.OutputStream JavaDoc;
24 import java.util.HashSet JavaDoc;
25 import java.util.Set JavaDoc;
26
27 import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm;
28 import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException;
29 import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException;
30 import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
31 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
32 import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException;
33 import com.sun.org.apache.xml.internal.security.transforms.Transform;
34 import com.sun.org.apache.xml.internal.security.transforms.TransformationException;
35 import com.sun.org.apache.xml.internal.security.transforms.Transforms;
36 import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNamespaces;
37 import com.sun.org.apache.xml.internal.security.utils.Base64;
38 import com.sun.org.apache.xml.internal.security.utils.Constants;
39 import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream;
40 import com.sun.org.apache.xml.internal.security.utils.IdResolver;
41 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
42 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
43 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
44 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver;
45 import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException;
46 import org.w3c.dom.Attr JavaDoc;
47 import org.w3c.dom.Document JavaDoc;
48 import org.w3c.dom.Element JavaDoc;
49 import org.w3c.dom.Node JavaDoc;
50 import org.w3c.dom.Text JavaDoc;
51
52
53 /**
54  * Handles <code>&lt;ds:Reference&gt;</code> elements.
55  *
56  * This includes:
57  *
58  * Constuct a <CODE>ds:Reference</CODE> from an {@link org.w3c.dom.Element}.
59  *
60  * <p>Create a new reference</p>
61  * <pre>
62  * Document _doc;
63  * MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
64  * Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
65  * "http://localhost/1.gif",
66  * (Transforms) null, sha1);
67  * Element refElem = ref.toElement(_doc);
68  * </pre>
69  *
70  * <p>Verify a reference</p>
71  * <pre>
72  * Element refElem = _doc.getElement("Reference"); // PSEUDO
73  * Reference ref = new Reference(refElem);
74  * String url = ref.getURI();
75  * ref.setData(new XMLSignatureInput(new FileInputStream(url)));
76  * if (ref.verify()) {
77  * System.out.println("verified");
78  * }
79  * </pre>
80  *
81  * <pre>
82  * &lt;element name="Reference" type="ds:ReferenceType"/&gt;
83  * &lt;complexType name="ReferenceType"&gt;
84  * &lt;sequence&gt;
85  * &lt;element ref="ds:Transforms" minOccurs="0"/&gt;
86  * &lt;element ref="ds:DigestMethod"/&gt;
87  * &lt;element ref="ds:DigestValue"/&gt;
88  * &lt;/sequence&gt;
89  * &lt;attribute name="Id" type="ID" use="optional"/&gt;
90  * &lt;attribute name="URI" type="anyURI" use="optional"/&gt;
91  * &lt;attribute name="Type" type="anyURI" use="optional"/&gt;
92  * &lt;/complexType&gt;
93  * </pre>
94  *
95  * @author Christian Geuer-Pollmann
96  * @see ObjectContainer
97  * @see Manifest
98  */

99 public class Reference extends SignatureElementProxy {
100
101    /** {@link java.util.logging} logging facility */
102     static java.util.logging.Logger JavaDoc log =
103         java.util.logging.Logger.getLogger(Reference.class.getName());
104
105    /** Field OBJECT_URI */
106    public static final String JavaDoc OBJECT_URI = Constants.SignatureSpecNS
107                                            + Constants._TAG_OBJECT;
108
109    /** Field MANIFEST_URI */
110    public static final String JavaDoc MANIFEST_URI = Constants.SignatureSpecNS
111                                              + Constants._TAG_MANIFEST;
112    //J-
113
Manifest _manifest = null;
114    XMLSignatureInput _transformsOutput;
115    //J+
116

117    /**
118     * Constructor Reference
119     *
120     * @param doc the {@link Document} in which <code>XMLsignature</code> is placed
121     * @param BaseURI the URI of the resource where the XML instance will be stored
122     * @param ReferenceURI URI indicate where is data which will digested
123     * @param manifest
124     * @param transforms {@link Transforms} applied to data
125     * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data
126     * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
127     * @throws XMLSignatureException
128     */

129    protected Reference(Document JavaDoc doc, String JavaDoc BaseURI, String JavaDoc ReferenceURI, Manifest manifest, Transforms transforms, String JavaDoc messageDigestAlgorithm)
130            throws XMLSignatureException {
131
132       super(doc);
133
134       XMLUtils.addReturnToElement(this._constructionElement);
135
136       this._baseURI = BaseURI;
137       this._manifest = manifest;
138
139       this.setURI(ReferenceURI);
140
141       // important: The ds:Reference must be added to the associated ds:Manifest
142
// or ds:SignedInfo _before_ the this.resolverResult() is called.
143
// this._manifest.appendChild(this._constructionElement);
144
// this._manifest.appendChild(this._doc.createTextNode("\n"));
145

146       if (transforms != null) {
147          this._constructionElement.appendChild(transforms.getElement());
148          XMLUtils.addReturnToElement(this._constructionElement);
149       }
150       {
151          MessageDigestAlgorithm mda =
152             MessageDigestAlgorithm.getInstance(this._doc,
153                                                messageDigestAlgorithm);
154
155          this._constructionElement.appendChild(mda.getElement());
156          XMLUtils.addReturnToElement(this._constructionElement);
157       }
158       {
159          Element JavaDoc digestValueElement =
160             XMLUtils.createElementInSignatureSpace(this._doc,
161                                                    Constants._TAG_DIGESTVALUE);
162
163          this._constructionElement.appendChild(digestValueElement);
164          XMLUtils.addReturnToElement(this._constructionElement);
165       }
166    }
167
168
169    /**
170     * Build a {@link Reference} from an {@link Element}
171     *
172     * @param element <code>Reference</code> element
173     * @param BaseURI the URI of the resource where the XML instance was stored
174     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. We need this because the Manifest has the individual {@link ResourceResolver}s whcih have been set by the user
175     * @throws XMLSecurityException
176     */

177    protected Reference(Element JavaDoc element, String JavaDoc BaseURI, Manifest manifest)
178            throws XMLSecurityException {
179
180       super(element, BaseURI);
181
182       this._manifest = manifest;
183    }
184
185    /**
186     * Returns {@link MessageDigestAlgorithm}
187     *
188     *
189     * @return {@link MessageDigestAlgorithm}
190     *
191     * @throws XMLSignatureException
192     */

193    public MessageDigestAlgorithm getMessageDigestAlgorithm()
194            throws XMLSignatureException {
195
196       Element JavaDoc digestMethodElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
197             Constants._TAG_DIGESTMETHOD,0);
198
199       if (digestMethodElem == null) {
200          return null;
201       }
202
203       String JavaDoc uri = digestMethodElem.getAttributeNS(null,
204          Constants._ATT_ALGORITHM);
205
206       if (uri == null) {
207           return null;
208       }
209
210       return MessageDigestAlgorithm.getInstance(this._doc, uri);
211    }
212
213    /**
214     * Sets the <code>URI</code> of this <code>Reference</code> element
215     *
216     * @param URI the <code>URI</code> of this <code>Reference</code> element
217     */

218    public void setURI(String JavaDoc URI) {
219
220       if ((this._state == MODE_SIGN) && (URI != null)) {
221          this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
222                                                   URI);
223       }
224    }
225
226    /**
227     * Returns the <code>URI</code> of this <code>Reference</code> element
228     *
229     * @return URI the <code>URI</code> of this <code>Reference</code> element
230     */

231    public String JavaDoc getURI() {
232       return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
233    }
234
235    /**
236     * Sets the <code>Id</code> attribute of this <code>Reference</code> element
237     *
238     * @param Id the <code>Id</code> attribute of this <code>Reference</code> element
239     */

240    public void setId(String JavaDoc Id) {
241
242       if ((this._state == MODE_SIGN) && (Id != null)) {
243          this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
244          IdResolver.registerElementById(this._constructionElement, Id);
245       }
246    }
247
248    /**
249     * Returns the <code>Id</code> attribute of this <code>Reference</code> element
250     *
251     * @return Id the <code>Id</code> attribute of this <code>Reference</code> element
252     */

253    public String JavaDoc getId() {
254       return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
255    }
256
257    /**
258     * Sets the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
259     *
260     * @param Type the <code>type</code> attribute of the Reference
261     */

262    public void setType(String JavaDoc Type) {
263
264       if ((this._state == MODE_SIGN) && (Type != null)) {
265          this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
266                                                   Type);
267       }
268    }
269
270    /**
271     * Return the <code>type</code> atttibute of the Reference indicate whether an <code>ds:Object</code>, <code>ds:SignatureProperty</code>, or <code>ds:Manifest</code> element
272     *
273     * @return the <code>type</code> attribute of the Reference
274     */

275    public String JavaDoc getType() {
276       return this._constructionElement.getAttributeNS(null,
277               Constants._ATT_TYPE);
278    }
279
280    /**
281     * Method isReferenceToObject
282     *
283     * This returns true if the <CODE>Type</CODE> attribute of the
284     * <CODE>Refernce</CODE> element points to a <CODE>#Object</CODE> element
285     *
286     * @return true if the Reference type indicates that this Reference points to an <code>Object</code>
287     */

288    public boolean typeIsReferenceToObject() {
289
290       if ((this.getType() != null)
291               && this.getType().equals(Reference.OBJECT_URI)) {
292          return true;
293       }
294
295       return false;
296    }
297
298    /**
299     * Method isReferenceToManifest
300     *
301     * This returns true if the <CODE>Type</CODE> attribute of the
302     * <CODE>Refernce</CODE> element points to a <CODE>#Manifest</CODE> element
303     *
304     * @return true if the Reference type indicates that this Reference points to a {@link Manifest}
305     */

306    public boolean typeIsReferenceToManifest() {
307
308       if ((this.getType() != null)
309               && this.getType().equals(Reference.MANIFEST_URI)) {
310          return true;
311       }
312
313       return false;
314    }
315
316    /**
317     * Method setDigestValueElement
318     *
319     * @param digestValue
320     */

321    private void setDigestValueElement(byte[] digestValue)
322    {
323
324       if (this._state == MODE_SIGN) {
325          Element JavaDoc digestValueElement =XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
326                  Constants._TAG_DIGESTVALUE,0);
327          Node JavaDoc n=digestValueElement.getFirstChild();
328          while (n!=null) {
329                digestValueElement.removeChild(n);
330                n = n.getNextSibling();
331          }
332
333          String JavaDoc base64codedValue = Base64.encode(digestValue);
334          Text JavaDoc t = this._doc.createTextNode(base64codedValue);
335
336          digestValueElement.appendChild(t);
337       }
338    }
339
340    /**
341     * Method generateDigestValue
342     *
343     * @throws ReferenceNotInitializedException
344     * @throws XMLSignatureException
345     */

346    public void generateDigestValue()
347            throws XMLSignatureException, ReferenceNotInitializedException {
348
349       if (this._state == MODE_SIGN) {
350
351          this.setDigestValueElement(this.calculateDigest());
352       }
353    }
354
355    /**
356     * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
357     * @return the XMLSignatureInput of the source of this reference
358     * @throws ReferenceNotInitializedException If the resolver found any
359     * problem resolving the reference
360     */

361    public XMLSignatureInput getContentsBeforeTransformation()
362            throws ReferenceNotInitializedException {
363
364       try {
365          Attr JavaDoc URIAttr = this._constructionElement.getAttributeNodeNS(null,
366             Constants._ATT_URI);
367          String JavaDoc URI;
368
369          if (URIAttr == null) {
370             URI = null;
371          } else {
372             URI = URIAttr.getNodeValue();
373          }
374
375          ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
376             this._baseURI, this._manifest._perManifestResolvers);
377
378          if (resolver == null) {
379             Object JavaDoc exArgs[] = { URI };
380
381             throw new ReferenceNotInitializedException(
382                "signature.Verification.Reference.NoInput", exArgs);
383          }
384
385          resolver.addProperties(this._manifest._resolverProperties);
386
387          XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
388                   
389
390          return input;
391       } catch (ResourceResolverException ex) {
392          throw new ReferenceNotInitializedException("empty", ex);
393       } catch (XMLSecurityException ex) {
394          throw new ReferenceNotInitializedException("empty", ex);
395       }
396    }
397
398    /**
399     * Returns the data which is referenced by the URI attribute. This method
400     * only works works after a call to verify.
401     * @return a XMLSignature with a byte array.
402     * @throws ReferenceNotInitializedException
403     *
404     * @deprecated use getContentsBeforeTransformation
405     */

406    public XMLSignatureInput getTransformsInput() throws ReferenceNotInitializedException
407     {
408         XMLSignatureInput input=getContentsBeforeTransformation();
409         XMLSignatureInput result;
410         try {
411             result = new XMLSignatureInput(input.getBytes());
412         } catch (CanonicalizationException ex) {
413              throw new ReferenceNotInitializedException("empty", ex);
414         } catch (IOException JavaDoc ex) {
415              throw new ReferenceNotInitializedException("empty", ex);
416         }
417         result.setSourceURI(input.getSourceURI());
418         return result;
419     
420    }
421
422    private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream JavaDoc os)
423            throws XMLSignatureException {
424
425       try {
426          Transforms transforms = this.getTransforms();
427          XMLSignatureInput output = null;
428
429          if (transforms != null) {
430             output = transforms.performTransforms(input,os);
431             this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
432

433             //this._transformsOutput.setSourceURI(output.getSourceURI());
434
} else {
435             output = input;
436          }
437
438          return output;
439       } catch (ResourceResolverException ex) {
440          throw new XMLSignatureException("empty", ex);
441       } catch (CanonicalizationException ex) {
442          throw new XMLSignatureException("empty", ex);
443       } catch (InvalidCanonicalizerException ex) {
444          throw new XMLSignatureException("empty", ex);
445       } catch (TransformationException ex) {
446          throw new XMLSignatureException("empty", ex);
447       } catch (XMLSecurityException ex) {
448          throw new XMLSignatureException("empty", ex);
449       }
450    }
451
452    /**
453     * Returns the XMLSignatureInput which is the result of the Transforms.
454     * @return a XMLSignatureInput with all transformations applied.
455     * @throws XMLSignatureException
456     */

457    public XMLSignatureInput getContentsAfterTransformation()
458            throws XMLSignatureException {
459
460       XMLSignatureInput input = this.getContentsBeforeTransformation();
461
462       return this.getContentsAfterTransformation(input, null);
463    }
464
465    /**
466     * This method returns the XMLSignatureInput which represents the node set before
467     * some kind of canonicalization is applied for the first time.
468     * @return Gets a the node doing everything till the first c14n is needed
469     *
470     * @throws XMLSignatureException
471     */

472    public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
473            throws XMLSignatureException {
474
475       try {
476          XMLSignatureInput input = this.getContentsBeforeTransformation();
477          XMLSignatureInput output = input;
478          Transforms transforms = this.getTransforms();
479
480          if (transforms != null) {
481             doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
482                Transform t = transforms.item(i);
483                String JavaDoc URI = t.getURI();
484
485                if (URI.equals(Transforms
486                        .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
487                           .equals(Transforms
488                              .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
489                                 .equals(Transforms
490                                    .TRANSFORM_C14N_OMIT_COMMENTS) || URI
491                                       .equals(Transforms
492                                          .TRANSFORM_C14N_WITH_COMMENTS)) {
493
494                   break doTransforms;
495                }
496
497                output = t.performTransform(output, null);
498             }
499
500             output.setSourceURI(input.getSourceURI());
501          }
502          return output;
503       } catch (IOException JavaDoc ex) {
504          throw new XMLSignatureException("empty", ex);
505       } catch (ResourceResolverException ex) {
506          throw new XMLSignatureException("empty", ex);
507       } catch (CanonicalizationException ex) {
508          throw new XMLSignatureException("empty", ex);
509       } catch (InvalidCanonicalizerException ex) {
510          throw new XMLSignatureException("empty", ex);
511       } catch (TransformationException ex) {
512          throw new XMLSignatureException("empty", ex);
513       } catch (XMLSecurityException ex) {
514          throw new XMLSignatureException("empty", ex);
515       }
516    }
517
518    /**
519     * Method getHTMLRepresentation
520     * @return The HTML of the transformation
521     * @throws XMLSignatureException
522     */

523    public String JavaDoc getHTMLRepresentation() throws XMLSignatureException {
524
525       try {
526          XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
527          Set JavaDoc inclusiveNamespaces = new HashSet JavaDoc();
528
529          {
530             Transforms transforms = this.getTransforms();
531             Transform c14nTransform = null;
532
533             if (transforms != null) {
534                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
535                   Transform t = transforms.item(i);
536                   String JavaDoc URI = t.getURI();
537
538                   if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
539                           || URI.equals(
540                              Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
541                      c14nTransform = t;
542
543                      break doTransforms;
544                   }
545                }
546             }
547
548             if (c14nTransform != null) {
549
550                if (c14nTransform
551                        .length(InclusiveNamespaces
552                           .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
553                           ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
554
555                   // there is one InclusiveNamespaces element
556
InclusiveNamespaces in = new InclusiveNamespaces(
557                         XMLUtils.selectNode(
558                         c14nTransform.getElement().getFirstChild(),
559                         InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
560                         InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
561
562                   inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
563                      in.getInclusiveNamespaces());
564                }
565             }
566          }
567
568          return nodes.getHTMLRepresentation(inclusiveNamespaces);
569       } catch (TransformationException ex) {
570          throw new XMLSignatureException("empty", ex);
571       } catch (InvalidTransformException ex) {
572          throw new XMLSignatureException("empty", ex);
573       } catch (XMLSecurityException ex) {
574          throw new XMLSignatureException("empty", ex);
575       }
576    }
577
578    /**
579     * This method only works works after a call to verify.
580     * @return the transformed output(i.e. what is going to be digested).
581     */

582    public XMLSignatureInput getTransformsOutput() {
583       return this._transformsOutput;
584    }
585
586    /**
587     * This method returns the {@link XMLSignatureInput} which is referenced by the
588     * <CODE>URI</CODE> Attribute.
589     * @param os where to write the transformation can be null.
590     * @return the element to digest
591     *
592     * @throws XMLSignatureException
593     * @see Manifest#verifyReferences()
594     */

595    protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream JavaDoc os)
596            throws XMLSignatureException {
597
598       try {
599          XMLSignatureInput input = this.getContentsBeforeTransformation();
600          XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
601
602          /* at this stage, this._transformsInput and this._transformsOutput
603           * contain a huge amount of nodes. When we do not cache these nodes
604           * but only preserve the octets, the memory footprint is dramatically
605           * reduced.
606           */

607
608          this._transformsOutput = output;
609
610          return output;
611       } catch (XMLSecurityException ex) {
612          throw new ReferenceNotInitializedException("empty", ex);
613       }
614    }
615
616    /**
617     * Method getTransforms
618     *
619     * @return The transforms that applied this reference.
620     * @throws InvalidTransformException
621     * @throws TransformationException
622     * @throws XMLSecurityException
623     * @throws XMLSignatureException
624     */

625    public Transforms getTransforms()
626            throws XMLSignatureException, InvalidTransformException,
627                   TransformationException, XMLSecurityException {
628
629       Element JavaDoc transformsElement = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
630             Constants._TAG_TRANSFORMS,0);
631
632       if (transformsElement != null) {
633          Transforms transforms = new Transforms(transformsElement,
634                                                 this._baseURI);
635
636          return transforms;
637       }
638        return null;
639    }
640
641    /**
642     * Method getReferencedBytes
643     *
644     * @return the bytes that will be used to generated digest.
645     * @throws ReferenceNotInitializedException
646     * @throws XMLSignatureException
647     */

648    public byte[] getReferencedBytes()
649            throws ReferenceNotInitializedException, XMLSignatureException {
650     try {
651         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
652
653         byte[] signedBytes = output.getBytes();
654
655         return signedBytes;
656      } catch (IOException JavaDoc ex) {
657         throw new ReferenceNotInitializedException("empty", ex);
658      } catch (CanonicalizationException ex) {
659         throw new ReferenceNotInitializedException("empty", ex);
660      }
661
662    }
663
664
665    /**
666     * Method resolverResult
667     *
668     * @return reference Calculate the digest of this reference.
669     * @throws ReferenceNotInitializedException
670     * @throws XMLSignatureException
671     */

672    private byte[] calculateDigest()
673            throws ReferenceNotInitializedException, XMLSignatureException {
674
675       try {
676          
677          MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
678
679          mda.reset();
680          DigesterOutputStream diOs=new DigesterOutputStream(mda);
681          OutputStream JavaDoc os=new UnsyncBufferedOutputStream(diOs);
682          XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);
683          output.updateOutputStream(os);
684          os.flush();
685          //this.getReferencedBytes(diOs);
686
//mda.update(data);
687

688          return diOs.getDigestValue();
689       } catch (XMLSecurityException ex) {
690          throw new ReferenceNotInitializedException("empty", ex);
691       } catch (IOException JavaDoc ex) {
692          throw new ReferenceNotInitializedException("empty", ex);
693     }
694    }
695
696    /**
697     * Returns the digest value.
698     *
699     * @return the digest value.
700     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
701     * @throws XMLSecurityException if the Reference does not contain a DigestValue element
702     */

703    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
704       Element JavaDoc digestValueElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild()
705             ,Constants._TAG_DIGESTVALUE,0);
706       if (digestValueElem == null) {
707           // The required element is not in the XML!
708
Object JavaDoc[] exArgs ={ Constants._TAG_DIGESTVALUE,
709                              Constants.SignatureSpecNS };
710           throw new XMLSecurityException(
711                     "signature.Verification.NoSignatureElement",
712                     exArgs);
713       }
714       byte[] elemDig = Base64.decode(digestValueElem);
715       return elemDig;
716    }
717
718
719    /**
720     * Tests reference valdiation is success or false
721     *
722     * @return true if reference valdiation is success, otherwise false
723     * @throws ReferenceNotInitializedException
724     * @throws XMLSecurityException
725     */

726    public boolean verify()
727            throws ReferenceNotInitializedException, XMLSecurityException {
728
729       byte[] elemDig = this.getDigestValue();
730       byte[] calcDig = this.calculateDigest();
731       boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
732
733       if (!equal) {
734          log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
735       } else {
736          if (log.isLoggable(java.util.logging.Level.INFO)) log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
737       }
738
739       return equal;
740    }
741
742    /**
743     * Method getBaseLocalName
744     * @inheritDoc
745     *
746     */

747    public String JavaDoc getBaseLocalName() {
748       return Constants._TAG_REFERENCE;
749    }
750 }
751
Popular Tags