FileDocCategorySizeDatePackage
Reference.javaAPI DocJava SE 6 API26275Tue Jun 10 00:23:04 BST 2008com.sun.org.apache.xml.internal.security.signature

Reference

public class Reference extends SignatureElementProxy
Handles <ds:Reference> elements. This includes: Constuct a ds:Reference from an {@link org.w3c.dom.Element}.

Create a new reference

Document _doc;
MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
"http://localhost/1.gif",
(Transforms) null, sha1);
Element refElem = ref.toElement(_doc);

Verify a reference

Element refElem = _doc.getElement("Reference"); // PSEUDO
Reference ref = new Reference(refElem);
String url = ref.getURI();
ref.setData(new XMLSignatureInput(new FileInputStream(url)));
if (ref.verify()) {
System.out.println("verified");
}
<element name="Reference" type="ds:ReferenceType"/>
<complexType name="ReferenceType">
<sequence>
<element ref="ds:Transforms" minOccurs="0"/>
<element ref="ds:DigestMethod"/>
<element ref="ds:DigestValue"/>
</sequence>
<attribute name="Id" type="ID" use="optional"/>
<attribute name="URI" type="anyURI" use="optional"/>
<attribute name="Type" type="anyURI" use="optional"/>
</complexType>
author
Christian Geuer-Pollmann
see
ObjectContainer
see
Manifest

Fields Summary
static Logger
log
{@link java.util.logging} logging facility
public static final String
OBJECT_URI
Field OBJECT_URI
public static final String
MANIFEST_URI
Field MANIFEST_URI
Manifest
_manifest
XMLSignatureInput
_transformsOutput
Constructors Summary
protected Reference(Document doc, String BaseURI, String ReferenceURI, Manifest manifest, Transforms transforms, String messageDigestAlgorithm)
Constructor Reference

param
doc the {@link Document} in which XMLsignature is placed
param
BaseURI the URI of the resource where the XML instance will be stored
param
ReferenceURI URI indicate where is data which will digested
param
manifest
param
transforms {@link Transforms} applied to data
param
messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
throws
XMLSignatureException

   //J+

                                                                           
               
             

      super(doc);

      XMLUtils.addReturnToElement(this._constructionElement);

      this._baseURI = BaseURI;
      this._manifest = manifest;

      this.setURI(ReferenceURI);

      // important: The ds:Reference must be added to the associated ds:Manifest
      //            or ds:SignedInfo _before_ the this.resolverResult() is called.
      // this._manifest.appendChild(this._constructionElement);
      // this._manifest.appendChild(this._doc.createTextNode("\n"));

      if (transforms != null) {
         this._constructionElement.appendChild(transforms.getElement());
         XMLUtils.addReturnToElement(this._constructionElement);
      }
      {
         MessageDigestAlgorithm mda =
            MessageDigestAlgorithm.getInstance(this._doc,
                                               messageDigestAlgorithm);

         this._constructionElement.appendChild(mda.getElement());
         XMLUtils.addReturnToElement(this._constructionElement);
      }
      {
         Element digestValueElement =
            XMLUtils.createElementInSignatureSpace(this._doc,
                                                   Constants._TAG_DIGESTVALUE);

         this._constructionElement.appendChild(digestValueElement);
         XMLUtils.addReturnToElement(this._constructionElement);
      }
   
protected Reference(Element element, String BaseURI, Manifest manifest)
Build a {@link Reference} from an {@link Element}

param
element Reference element
param
BaseURI the URI of the resource where the XML instance was stored
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
throws
XMLSecurityException


      super(element, BaseURI);      

      this._manifest = manifest;
   
Methods Summary
private byte[]calculateDigest()
Method resolverResult

return
reference Calculate the digest of this reference.
throws
ReferenceNotInitializedException
throws
XMLSignatureException


      try {
         
         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();

         mda.reset();
         DigesterOutputStream diOs=new DigesterOutputStream(mda);
         OutputStream os=new UnsyncBufferedOutputStream(diOs);
         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);         
         output.updateOutputStream(os);
         os.flush();
         //this.getReferencedBytes(diOs);
         //mda.update(data);

         return diOs.getDigestValue();
      } catch (XMLSecurityException ex) {
         throw new ReferenceNotInitializedException("empty", ex);
      } catch (IOException ex) {
      	 throw new ReferenceNotInitializedException("empty", ex);
	}
   
protected com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputdereferenceURIandPerformTransforms(java.io.OutputStream os)
This method returns the {@link XMLSignatureInput} which is referenced by the URI Attribute.

param
os where to write the transformation can be null.
return
the element to digest
throws
XMLSignatureException
see
Manifest#verifyReferences()


      try {
         XMLSignatureInput input = this.getContentsBeforeTransformation();
         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);

         /* at this stage, this._transformsInput and this._transformsOutput
          * contain a huge amount of nodes. When we do not cache these nodes
          * but only preserve the octets, the memory footprint is dramatically
          * reduced.
          */

         this._transformsOutput = output;

         return output;
      } catch (XMLSecurityException ex) {
         throw new ReferenceNotInitializedException("empty", ex);
      }
   
public voidgenerateDigestValue()
Method generateDigestValue

throws
ReferenceNotInitializedException
throws
XMLSignatureException


      if (this._state == MODE_SIGN) {

         this.setDigestValueElement(this.calculateDigest());
      }
   
public java.lang.StringgetBaseLocalName()
Method getBaseLocalName

inheritDoc

      return Constants._TAG_REFERENCE;
   
private com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetContentsAfterTransformation(com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput input, java.io.OutputStream os)


      try {
         Transforms transforms = this.getTransforms();
         XMLSignatureInput output = null;

         if (transforms != null) {
            output = transforms.performTransforms(input,os);
            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());

            //this._transformsOutput.setSourceURI(output.getSourceURI());
         } else {
            output = input;
         }

         return output;
      } catch (ResourceResolverException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (CanonicalizationException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (InvalidCanonicalizerException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (TransformationException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (XMLSecurityException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   
public com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetContentsAfterTransformation()
Returns the XMLSignatureInput which is the result of the Transforms.

return
a XMLSignatureInput with all transformations applied.
throws
XMLSignatureException


      XMLSignatureInput input = this.getContentsBeforeTransformation();

      return this.getContentsAfterTransformation(input, null);
   
public com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetContentsBeforeTransformation()
Returns the XMLSignatureInput which is created by de-referencing the URI attribute.

return
the XMLSignatureInput of the source of this reference
throws
ReferenceNotInitializedException If the resolver found any problem resolving the reference


      try {
         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
            Constants._ATT_URI);
         String URI;

         if (URIAttr == null) {
            URI = null;
         } else {
            URI = URIAttr.getNodeValue();
         }

         ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
            this._baseURI, this._manifest._perManifestResolvers);

         if (resolver == null) {
            Object exArgs[] = { URI };

            throw new ReferenceNotInitializedException(
               "signature.Verification.Reference.NoInput", exArgs);
         }

         resolver.addProperties(this._manifest._resolverProperties);

         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
                  

         return input;
      }  catch (ResourceResolverException ex) {
         throw new ReferenceNotInitializedException("empty", ex);
      } catch (XMLSecurityException ex) {
         throw new ReferenceNotInitializedException("empty", ex);
      }
   
public byte[]getDigestValue()
Returns the digest value.

return
the digest value.
throws
Base64DecodingException if Reference contains no proper base64 encoded data.
throws
XMLSecurityException if the Reference does not contain a DigestValue element

      Element digestValueElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild()
            ,Constants._TAG_DIGESTVALUE,0);
	  if (digestValueElem == null) {
		  // The required element is not in the XML!
		  Object[] exArgs ={ Constants._TAG_DIGESTVALUE, 
							 Constants.SignatureSpecNS };
		  throw new XMLSecurityException(
					"signature.Verification.NoSignatureElement", 
					exArgs);
	  }
      byte[] elemDig = Base64.decode(digestValueElem);
      return elemDig;
   
public java.lang.StringgetHTMLRepresentation()
Method getHTMLRepresentation

return
The HTML of the transformation
throws
XMLSignatureException


      try {
         XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
         Set inclusiveNamespaces = new HashSet();

         {
            Transforms transforms = this.getTransforms();
            Transform c14nTransform = null;

            if (transforms != null) {
               doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
                  Transform t = transforms.item(i);
                  String URI = t.getURI();

                  if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
                          || URI.equals(
                             Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
                     c14nTransform = t;

                     break doTransforms;
                  }
               }
            }

            if (c14nTransform != null) {

               if (c14nTransform
                       .length(InclusiveNamespaces
                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {

                  // there is one InclusiveNamespaces element
                  InclusiveNamespaces in = new InclusiveNamespaces(
                        XMLUtils.selectNode(
                        c14nTransform.getElement().getFirstChild(),
						InclusiveNamespaces.ExclusiveCanonicalizationNamespace, 
                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());

                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
                     in.getInclusiveNamespaces());
               }
            }
         }

         return nodes.getHTMLRepresentation(inclusiveNamespaces);
      } catch (TransformationException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (InvalidTransformException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (XMLSecurityException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   
public java.lang.StringgetId()
Returns the Id attribute of this Reference element

return
Id the Id attribute of this Reference element

      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
   
public com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithmgetMessageDigestAlgorithm()
Returns {@link MessageDigestAlgorithm}

return
{@link MessageDigestAlgorithm}
throws
XMLSignatureException


      Element digestMethodElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
            Constants._TAG_DIGESTMETHOD,0);

      if (digestMethodElem == null) {
         return null;
      }

      String uri = digestMethodElem.getAttributeNS(null,
         Constants._ATT_ALGORITHM);

	  if (uri == null) {
		  return null;
	  }

      return MessageDigestAlgorithm.getInstance(this._doc, uri);
   
public com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetNodesetBeforeFirstCanonicalization()
This method returns the XMLSignatureInput which represents the node set before some kind of canonicalization is applied for the first time.

return
Gets a the node doing everything till the first c14n is needed
throws
XMLSignatureException


      try {
         XMLSignatureInput input = this.getContentsBeforeTransformation();
         XMLSignatureInput output = input;
         Transforms transforms = this.getTransforms();

         if (transforms != null) {
            doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
               Transform t = transforms.item(i);
               String URI = t.getURI();

               if (URI.equals(Transforms
                       .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
                          .equals(Transforms
                             .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
                                .equals(Transforms
                                   .TRANSFORM_C14N_OMIT_COMMENTS) || URI
                                      .equals(Transforms
                                         .TRANSFORM_C14N_WITH_COMMENTS)) {

                  break doTransforms;
               }

               output = t.performTransform(output, null);
            }

            output.setSourceURI(input.getSourceURI());
         }
         return output;
      } catch (IOException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (ResourceResolverException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (CanonicalizationException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (InvalidCanonicalizerException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (TransformationException ex) {
         throw new XMLSignatureException("empty", ex);
      } catch (XMLSecurityException ex) {
         throw new XMLSignatureException("empty", ex);
      }
   
public byte[]getReferencedBytes()
Method getReferencedBytes

return
the bytes that will be used to generated digest.
throws
ReferenceNotInitializedException
throws
XMLSignatureException

    try {
        XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);

        byte[] signedBytes = output.getBytes();

        return signedBytes;
     } catch (IOException ex) {
        throw new ReferenceNotInitializedException("empty", ex);
     } catch (CanonicalizationException ex) {
        throw new ReferenceNotInitializedException("empty", ex);
     } 

   
public com.sun.org.apache.xml.internal.security.transforms.TransformsgetTransforms()
Method getTransforms

return
The transforms that applied this reference.
throws
InvalidTransformException
throws
TransformationException
throws
XMLSecurityException
throws
XMLSignatureException


      Element transformsElement = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
            Constants._TAG_TRANSFORMS,0);

      if (transformsElement != null) {
         Transforms transforms = new Transforms(transformsElement,
                                                this._baseURI);

         return transforms;
      } 
       return null;      
   
public com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetTransformsInput()
Returns the data which is referenced by the URI attribute. This method only works works after a call to verify.

return
a XMLSignature with a byte array.
throws
ReferenceNotInitializedException
deprecated
use getContentsBeforeTransformation

  
   		XMLSignatureInput input=getContentsBeforeTransformation();
   		XMLSignatureInput result;
		try {
			result = new XMLSignatureInput(input.getBytes());
		} catch (CanonicalizationException ex) {
			 throw new ReferenceNotInitializedException("empty", ex);
		} catch (IOException ex) {
			 throw new ReferenceNotInitializedException("empty", ex);
		}
		result.setSourceURI(input.getSourceURI());   
		return result;
	
   
public com.sun.org.apache.xml.internal.security.signature.XMLSignatureInputgetTransformsOutput()
This method only works works after a call to verify.

return
the transformed output(i.e. what is going to be digested).

      return this._transformsOutput;
   
public java.lang.StringgetType()
Return the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element

return
the type attribute of the Reference

      return this._constructionElement.getAttributeNS(null,
              Constants._ATT_TYPE);
   
public java.lang.StringgetURI()
Returns the URI of this Reference element

return
URI the URI of this Reference element

      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
   
private voidsetDigestValueElement(byte[] digestValue)
Method setDigestValueElement

param
digestValue


      if (this._state == MODE_SIGN) {
         Element digestValueElement =XMLUtils.selectDsNode(this._constructionElement.getFirstChild(),
                 Constants._TAG_DIGESTVALUE,0);
         Node n=digestValueElement.getFirstChild();
         while (n!=null) {
               digestValueElement.removeChild(n);
               n = n.getNextSibling();
         }

         String base64codedValue = Base64.encode(digestValue);
         Text t = this._doc.createTextNode(base64codedValue);

         digestValueElement.appendChild(t);
      }
   
public voidsetId(java.lang.String Id)
Sets the Id attribute of this Reference element

param
Id the Id attribute of this Reference element


      if ((this._state == MODE_SIGN) && (Id != null)) {
         this._constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
         IdResolver.registerElementById(this._constructionElement, Id);
      }
   
public voidsetType(java.lang.String Type)
Sets the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element

param
Type the type attribute of the Reference


      if ((this._state == MODE_SIGN) && (Type != null)) {
         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
                                                  Type);
      }
   
public voidsetURI(java.lang.String URI)
Sets the URI of this Reference element

param
URI the URI of this Reference element


      if ((this._state == MODE_SIGN) && (URI != null)) {
         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
                                                  URI);
      }
   
public booleantypeIsReferenceToManifest()
Method isReferenceToManifest This returns true if the Type attribute of the Refernce element points to a #Manifest element

return
true if the Reference type indicates that this Reference points to a {@link Manifest}


      if ((this.getType() != null)
              && this.getType().equals(Reference.MANIFEST_URI)) {
         return true;
      }

      return false;
   
public booleantypeIsReferenceToObject()
Method isReferenceToObject This returns true if the Type attribute of the Refernce element points to a #Object element

return
true if the Reference type indicates that this Reference points to an Object


      if ((this.getType() != null)
              && this.getType().equals(Reference.OBJECT_URI)) {
         return true;
      }

      return false;
   
public booleanverify()
Tests reference valdiation is success or false

return
true if reference valdiation is success, otherwise false
throws
ReferenceNotInitializedException
throws
XMLSecurityException


      byte[] elemDig = this.getDigestValue();
      byte[] calcDig = this.calculateDigest();
      boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);

      if (!equal) {
         log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
      } else {
         if (log.isLoggable(java.util.logging.Level.INFO))                                  log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
      }

      return equal;