You are viewing a plain text version of this content. The canonical link for it is here.
Posted to tsik-dev@ws.apache.org by ha...@apache.org on 2005/08/08 22:03:01 UTC

svn commit: r230871 [22/61] - in /incubator/tsik/trunk: ./ data/ data/schema/ resources/ resources/junit/ src/ src/org/ src/org/apache/ src/org/apache/tsik/ src/org/apache/tsik/c14n/ src/org/apache/tsik/c14n/elements/ src/org/apache/tsik/common/ src/or...

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Signer.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Signer.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Signer.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Signer.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,967 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PrivateKey;
+import java.security.PublicKey;
+import java.security.SignatureException;
+import java.security.cert.CertificateException; 
+import java.security.cert.X509Certificate;
+import java.security.interfaces.DSAPrivateKey;
+import java.security.interfaces.RSAPrivateKey;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Vector;
+import org.apache.tsik.c14n.elements.InclusiveNamespacesElement;
+import org.apache.tsik.common.Logger;
+import org.apache.tsik.common.LoggerFactory;
+import org.apache.tsik.domutil.DOMCursor;
+import org.apache.tsik.domutil.DOMWriteCursor;
+import org.apache.tsik.domutil.elements.ElementExtension;
+import org.apache.tsik.uuid.UUID;
+import org.apache.tsik.xmlsig.elements.KeyInfo;
+import org.apache.tsik.xmlsig.elements.ObjectElement;
+import org.apache.tsik.xmlsig.elements.Reference;
+import org.apache.tsik.xmlsig.elements.Signature;
+import org.apache.tsik.xmlsig.elements.SignedInfo;
+import org.apache.tsik.xmlsig.elements.Transform;
+import org.apache.tsik.xmlsig.elements.transforms.CanonicalizationTransform;
+import org.apache.tsik.xmlsig.elements.transforms.EnvelopedTransform;
+import org.apache.tsik.xmlsig.elements.transforms.ExclusiveC14nTransform;
+import org.apache.tsik.xpath.XPath;
+import org.apache.tsik.xpath.XPathException;
+import org.w3c.dom.Document;
+
+/**
+ * Signer signs XML documents according to the W3C XML-Signature
+ * specification 
+ * (<a href="http://www.w3.org/2000/09/xmldsig#">http://www.w3.org/2000/09/xmldsig#</a>).
+ * <p>
+ * There are three modes of operation specified:
+ * <ul>
+ * <li> Enveloping signature, in which the signature is over content
+ *      found within an Object element of the signature itself.</li>
+ *
+ * <li> Enveloped signature, in which the original document
+ *      contains the signature as an element.</li>
+ *
+ * <li> Detached signature. Similar to Enveloped signature, but
+ *      the Signature element is detached from the signed element.</li>
+ * </ul>
+ * </p>
+ *
+ * <p>This implementation supports all three modes of signing. Its usage:
+ * <ol>
+ * <li> Construct the Signer. You must provide the Signer with 
+ *   <ol>
+ *     <li>the XML document that you want to sign, and</li> 
+ *     <li>the signing key.</li>
+ *   </ol> 
+ *      Optionally, you can supply the verification key and attach it in the 
+ *      Signature.</li>
+ *
+ * <li> If desired, add references.</li>
+ *
+ * <li> <p>Sign the document. Explicitly choose which way to sign, or
+ *      accept default, depending on references added. You may supply
+ *      a location in the resulting Document where the Signature will
+ *      be placed. An enveloping signature will be created if you
+ *      provide no location for the signature.</p>
+ *
+ *      <p>You can choose whether to sign the document in place, or to
+ *      return a new, signed, document, leaving the original intact with
+ *      the <code>sign()</code> and <code>signInPlace()</code> APIs.</p></li>
+ *
+ * </ol>
+ * <p><B>Note:</B> An XML document may have several associated signatures, but 
+ * this API only
+ * supports a single signature. If you need to sign multiple times, create
+ * a new Signer on the result from <code>sign(</code> and then iterate.</p>
+ * 
+ * <p>Example usage:
+ * <pre>
+ *      Signer signer = new Signer(doc, privateKey, publicKey);
+ *
+ *      XPath loc1 = new XPath("id('someID')");
+ *      signer.addReference(loc1);
+ *
+ *      XPath loc2 = new XPath("/some/element");
+ *      signer.addReference(loc2);
+ *
+ *      XPath output = new XPath("/");
+ *      Document d = signer.sign(output);
+ * </pre></p>
+ *
+ * <p>In the example above , we sign a document and implicitly tell it
+ * to add the public verification key to its output. We supply two
+ * locations, <code>loc1</code> and <code>loc2</code>, to be signed (these 
+ * locations will be
+ * two references in the resulting signature) and a location, 
+ * <code>output</code>,
+ * where we want the resulting signature to be placed. Since we supply
+ * an output location, an enveloped signature will be created. If we had
+ * instead signed like this:
+ * <pre>
+ *      Document d = signer.sign();
+ * </pre>
+ * then we would have forced an enveloping signature.</p>
+ * 
+ * <p>Note that this API only allows XPath expressions that evaluate to 
+ * a single node. Nor are relative XPath expressions (e.g., "../element") 
+ * allowed since the Signature reference's context changes at the time
+ * of signing.</p>
+ */
+public class Signer 
+{
+    private static Logger log = LoggerFactory.getLogger(Signer.class);
+
+    private Vector refs = new Vector();
+    private DOMWriteCursor writeCursor = null;
+    private Signature signature;
+    private Document document;
+
+    private List inclusivePrefixList = null;
+    private boolean inPlace = false;
+
+    /**
+     * This signer will use the exclusive signature as defined
+     * by <code>http://www.w3.org/2001/10/xml-exc-c14n#</code>.
+     *
+     * <p>The exclusive c14n algorithm will be used for canonicalization
+     * of the signature, as well as for all added transformations<p>.
+     *
+     * @param list the inclusive prefix list as defined
+     *  by the specification. Any namespace prefix in the list
+     *  that are not visibly used in the context will be silently
+     *  ignored.
+     *
+     * @throws IllegalArgumentException if list is null. To specify 
+     * an empty list, use {@link java.util.Collections#EMPTY_LIST}
+     */
+    public void useExclusiveCanonicalizer(List list)
+    {
+        if (list == null){
+            throw new IllegalArgumentException("list cannot be null");
+        }
+        if (log.isDebugEnabled()){
+            log.debug("using exclusive c14n, include prefix:" + list);
+        }
+        SignedInfo signedInfo = signature.getSignedInfo();
+        signedInfo.useExclusiveCanonicalizer(list);
+        inclusivePrefixList = new Vector(list);
+    }
+
+    /**
+     * Creates a Signer with a signing key and a verifying key as
+     * part of the Signature element.
+     *
+     * @param doc the document that will be signed. Note that this 
+     *  document will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     * @param verificationKey a key that will be appended to the signature. 
+     *  This key can be used at verification time
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or
+     *  Hardware.
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     */
+    public Signer(Document doc, PrivateKey signingKey,
+                   PublicKey verificationKey)
+        throws InvalidKeyException, NoSuchAlgorithmException
+    {
+        this.create(doc, createSigningKey(signingKey), verificationKey);
+    }
+        
+    /**
+     * Creates a signer with a signing key. No verification key is 
+     * added to the signature.
+     * The recipient of the signed document must obtain this key from 
+     * a source other than the signed document.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or Hardware.
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     */
+    public Signer(Document doc, PrivateKey signingKey)
+        throws InvalidKeyException, NoSuchAlgorithmException 
+    {
+        this.create(doc, createSigningKey(signingKey));
+    }
+
+    /**
+     * Creates a signer with a signing key. No verification key is 
+     * added to the signature.
+     * The recipient of the signed document must obtain this key from 
+     * a source other than the signed document.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws InvalidKeyException TODO.
+     */
+    public Signer(Document doc, SigningKey signingKey)
+        throws InvalidKeyException, NoSuchAlgorithmException 
+    {
+        this.create(doc, signingKey);
+    }
+    
+    /**
+     * Creates a Signer with a signing key and a verifying key as
+     * part of the Signature element.
+     *
+     * @param doc the document that will be signed. Note that this 
+     *  document will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     * @param verifyingKey a key that will be appended to the signature. 
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws InvalidKeyException TODO.
+     */
+    public Signer(Document doc, 
+                  SigningKey signingKey, VerifyingKey verifyingKey)     
+        throws InvalidKeyException, NoSuchAlgorithmException
+    {
+        this.create(doc, signingKey, verifyingKey);
+    }
+
+    /**
+     * Creates a Signer with a private key and a certificate chain. The
+     * chain's first element (at index 0) is used for signing, the rest
+     * of the certificates will be appended into the X509Data element.
+     * <p>
+     * Only the first certificate in the chain will have its Issuer Serial
+     * information, Subject name and SKI copied; the rest of the 
+     * certificates will have only the X509Certificate.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     * @param certificateChain a X.509 certificate chain that will be 
+     *  output into the resulting document. 
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or Hardware
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws CertificateException if the certificate does not contain
+     *  a public RSA key, or certificate is not properly base64-encoded.
+     */
+    public Signer(Document doc, PrivateKey signingKey,
+                  X509Certificate[] certificateChain) 
+        throws InvalidKeyException, NoSuchAlgorithmException, 
+               CertificateException 
+    {
+        if ((certificateChain == null) || (certificateChain[0] == null)){
+            throw new 
+                IllegalArgumentException("certificate chain cannot be null");
+        }
+        this.create(doc, createSigningKey(signingKey));
+        setCertificateChain(certificateChain);
+    }
+
+    /**
+     * Creates a Signer with a private key and a certificate that contains
+     * a public key. No verification key is added to the signature.
+     * The recipient of the signed document is assumed to have knowledge of
+     * this key. The certificate passed is appended to the <code>KeyInfo</code>
+     * element.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     * @param certificate an X.509 certificate that will be output into the
+     *  resulting document.
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or Hardware
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws CertificateException if the certificate does not contain
+     *  a public RSA key, or certificate is not properly base64-encoded.
+     */
+    public Signer(Document doc, PrivateKey signingKey,
+                  X509Certificate certificate) 
+        throws InvalidKeyException, NoSuchAlgorithmException, 
+               CertificateException 
+    {
+        if (certificate == null){
+          throw new IllegalArgumentException("certificate cannot be null");
+        }
+        this.create(doc, createSigningKey(signingKey));
+        setCertificate(certificate);
+    }
+
+    /**
+     * Creates a Signer with a signing key and verifying key information.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     *
+     * @param keyInfo verifying key information that will be output into the
+     * resulting document. 
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or Hardware
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws CertificateException if the certificate does not contain
+     *  a public RSA key, or certificate is not properly base64-encoded.
+     */
+    public Signer(Document doc, SigningKey signingKey,
+                  org.apache.tsik.xmlsig.KeyInfo keyInfo)
+        throws InvalidKeyException, NoSuchAlgorithmException, 
+               CertificateException 
+    {
+        this.create(doc, signingKey);
+        setKeyInfo(keyInfo);
+    }
+
+    /**
+     * Creates a Signer with a private key and verifying key information.
+     *
+     * @param doc the document that will be signed. Note that this document 
+     *  will be cloned.
+     *
+     * @param signingKey the key used to sign.
+     *
+     * @param keyInfo verifying key information that will be output into the
+     * resulting document. 
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws InvalidKeyException if the key is not of type RSA or Hardware
+     * @throws NoSuchAlgorithmException if SHA1 is not available as digest
+     *  algorithm
+     * @throws CertificateException if the certificate does not contain
+     *  a public RSA key, or certificate is not properly base64-encoded.
+     */
+    public Signer(Document doc, PrivateKey signingKey,
+                  org.apache.tsik.xmlsig.KeyInfo keyInfo)
+        throws InvalidKeyException, NoSuchAlgorithmException, 
+               CertificateException 
+    {
+        this.create(doc, createSigningKey(signingKey));
+        setKeyInfo(keyInfo);
+    }
+
+    private void create(Document doc, SigningKey signingKey)
+        throws InvalidKeyException, 
+               NoSuchAlgorithmException 
+    {
+        this.create(doc, signingKey, (PublicKey) null);
+    }
+
+    private void create(Document doc, SigningKey signingKey, 
+                        PublicKey verificationKey) 
+        throws InvalidKeyException, 
+               NoSuchAlgorithmException 
+    {
+        createSignature(doc, signingKey);
+        if (verificationKey != null){
+            KeyInfo keyInfo = signature.getKeyInfo();
+            keyInfo.addKeyValue(verificationKey);
+        }
+    }
+
+    private void createWriteCursor()
+    {
+        if (writeCursor != null){
+            return;
+        }
+
+        if (inPlace){
+            if (log.isDebugEnabled()){
+                log.debug("signing in place");
+            }
+            writeCursor = new DOMWriteCursor(document);
+        } else {
+            if (log.isDebugEnabled()){
+                log.debug("signing new document");
+            }
+            DOMCursor foo = new DOMCursor(document);
+            writeCursor = new DOMWriteCursor();
+            writeCursor.copyUnder(foo);
+        }
+    }
+
+
+    private void create(Document doc, SigningKey signingKey, 
+                        final VerifyingKey verifyingKey) 
+        throws InvalidKeyException, 
+               NoSuchAlgorithmException 
+    {
+        createSignature(doc, signingKey);
+        if (verifyingKey != null){
+            final KeyInfo keyInfo = signature.getKeyInfo();
+            keyInfo.setExtension(new ElementExtension(){
+                    public void toXml(DOMWriteCursor c){
+                        verifyingKey.writeKeyInfo(c.getElement());
+                    }
+                    public ElementExtension fromXml(DOMCursor cursor) {
+                        return null;
+                    }
+                });
+        }
+    }
+
+    private void createSignature(Document doc, SigningKey signingKey) 
+        throws InvalidKeyException, 
+               NoSuchAlgorithmException 
+    {
+        if (doc == null){
+            throw new IllegalArgumentException("document cannot be null");
+        }
+        this.document = doc;
+        if (signingKey == null){
+            throw new IllegalArgumentException("signing key cannot be null");
+        }
+
+        signature = new Signature();
+        signature.setSigningKey(signingKey);
+    }
+
+    private SigningKey createSigningKey(PrivateKey signingKey) 
+        throws InvalidKeyException
+    { 
+        SigningKey sigKey;
+        if (signingKey instanceof RSAPrivateKey){
+            sigKey = new RSASigningKey(signingKey);
+        } else if (signingKey instanceof DSAPrivateKey){
+            sigKey = new DSASigningKey(signingKey);
+        } else if (signingKey instanceof HardwarePrivateKey){
+            sigKey = new HardwareSigningKey(signingKey);
+        } else {
+            throw new IllegalArgumentException("unknown signing key type");
+        }
+        return sigKey;
+    }
+
+    /**
+     * Checks for XPath expressions that will cause
+     * problem.
+     */
+    private void checkXPathExpression(XPath xpath) 
+        throws XPathException 
+    {
+
+        String s = xpath.getXPath();
+        if ("".equals(s)){
+            throw new XPathException("Empty XPath expression is not allowed");
+        }
+        if (s.indexOf("here()") != -1){
+            throw new XPathException("'here()' function cannot be used. "
+                                     + "Expression '" + s + "' is illegal.");
+        }
+        if (s.startsWith("..")){
+            throw new XPathException("Relative XPath expression '"
+                                     + s + "' is not allowed");
+        }
+
+        DOMCursor foo = new DOMCursor(document);
+        try {
+            foo.moveToXPath(xpath);
+        } catch (IllegalArgumentException e){
+            throw new XPathException(e.toString());
+        }
+
+    }
+
+
+    /**
+     * Adds a reference to an existing set of Elements in the document. These
+     * elements will be part of the data to be signed. Validation 
+     * of the XPath expression occurs at signing time.
+     *
+     * @param xpath The XPath expression pointing to a node set that the
+     *  Signature will be applied over.
+     */
+    public void addReference(XPath xpath){
+        refs.addElement(xpath);
+    }
+
+    private static void validateCertificate(X509Certificate certificate)
+        throws CertificateException
+    {
+        if (certificate == null) {
+            throw new IllegalArgumentException("certificate cannot be null");
+        }
+        certificate.checkValidity();
+    }
+
+    private static 
+        void validateCertificateChain(X509Certificate[] certificateChain)
+        throws CertificateException
+    {
+        if (certificateChain == null) {
+            throw new IllegalArgumentException("chain cannot be null");
+        }
+        if (certificateChain.length < 1) {
+            throw new IllegalArgumentException("chain cannot be empty");
+        }
+        validateCertificate(certificateChain[0]);
+        for (int i = 1; i < certificateChain.length; i++) {
+            if (certificateChain[i] != null) {
+                validateCertificate(certificateChain[i]);
+            }
+        }
+    }
+
+    private void setCertificate(X509Certificate certificate) 
+        throws CertificateException
+    {
+        validateCertificate(certificate);
+
+        KeyInfo keyInfo = signature.getKeyInfo();
+        keyInfo.addCertificate(certificate);
+        keyInfo.explodeCertificate();
+    }
+
+    private void setKeyInfo(org.apache.tsik.xmlsig.KeyInfo keyInfo) 
+        throws CertificateException
+    {
+        if (keyInfo != null) {
+            X509Certificate[] certChain = keyInfo.getCertificateChain();
+            if (certChain != null) {
+                validateCertificateChain(certChain);
+            }
+            signature.setKeyInfo(new KeyInfo(keyInfo));
+        }
+    }
+
+    private void setCertificateChain(X509Certificate[] certificateChain) 
+        throws CertificateException
+    {
+        validateCertificateChain(certificateChain);
+
+        KeyInfo keyInfo = signature.getKeyInfo();
+        keyInfo.addCertificateChain(certificateChain);
+        keyInfo.explodeCertificate();
+    }
+
+    private void addC14nTransform(Reference r)
+    {
+        if (inclusivePrefixList != null){
+            ElementExtension elemExt 
+                = new InclusiveNamespacesElement(inclusivePrefixList);
+            Transform t = new ExclusiveC14nTransform();
+            t.setExtension(elemExt);
+            r.addTransform(t);
+        } else {
+            r.addTransform(new CanonicalizationTransform());
+        }
+    }
+
+    /**
+     * Signs the document and returns it. The returned document contains
+     * a Signature element enveloping the signed data (replacing previous
+     * contents of document).
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing 
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node.
+     */
+    public void signInPlace() 
+        throws SignatureException, InvalidKeyException,
+               NoSuchAlgorithmException, XPathException
+    {
+        inPlace = true;
+        sign();
+    }
+
+    /**
+     * Signs the document and returns a new document containing
+     * a Signature element enveloping the signed data.
+     *
+     * @return the document with the signature.
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing 
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node.
+     */
+    public Document sign() throws SignatureException, InvalidKeyException,
+                                  NoSuchAlgorithmException, XPathException
+    {
+        boolean doTimes = log.isDebugEnabled();
+        long startTime = 0;
+        if (doTimes){
+            startTime = System.currentTimeMillis();
+        }
+        createWriteCursor();
+        int size = refs.size();
+        if (size == 0){
+            XPath xp = new XPath("/*");
+            addReference(xp);
+        }
+        Vector targets = new Vector();
+        size = refs.size();
+        for (int i=0; i < size; ++i){
+            XPath xp = (XPath) refs.elementAt(i);
+            checkXPathExpression(xp);
+
+            DOMCursor c = writeCursor.cloneCursor();
+            if (!c.moveToXPath(xp)){
+                throw new XPathException("XPath expression '" 
+                                         + xp.getXPath() + "'"
+                                     + " evaluates to nothing");
+            }
+            targets.add(c);
+        }
+
+        SignedInfo signedInfo = signature.getSignedInfo();
+        Enumeration enumer = targets.elements();
+        int i = 1;
+        while (enumer.hasMoreElements()){
+            DOMCursor c = (DOMCursor) enumer.nextElement();
+            Reference r = new Reference();
+            addC14nTransform(r);
+
+            String id = UUID.generate().toString();
+
+            ObjectElement o = new ObjectElement();
+            o.setElementCursor(c);
+            o.setId(id);
+
+            r.setUri("#" + id);
+            r.setTarget(o);
+            signedInfo.addReference(r);
+            ++i;
+        }
+        signature.addObjectsFromReferences(signedInfo.getReferences());
+
+        signedInfo.calculateReferences();
+        byte[] canon = signedInfo.canonicalize();
+
+        SigningKey signingKey = signature.getSigningKey();
+        byte[] bsig = signingKey.signData(canon);
+        signature.setSignatureValue(bsig);
+        
+        if (log.isDebugEnabled()){
+            log.debug("sign=" + signature);
+        }
+        DOMWriteCursor tempCursor = new DOMWriteCursor();
+        long t = 0;
+        if (doTimes){
+            t = System.currentTimeMillis();
+        }
+        signature.toXml(tempCursor);
+        long toXmlTime = 0;
+        if (doTimes){
+            toXmlTime = System.currentTimeMillis() - t;
+            t = System.currentTimeMillis();
+        }
+        if (inPlace){
+            writeCursor.moveToTop();
+            writeCursor.remove();
+            writeCursor.copyUnder(tempCursor);
+        } else {
+            writeCursor = tempCursor;
+        }
+        long copyTime, elapsedTime = 0;
+        if (doTimes){
+            copyTime = System.currentTimeMillis() - t;
+            elapsedTime = System.currentTimeMillis()-startTime;
+            log.debug("Time to sign: "+elapsedTime+" ms, of which toXml: "
+                      + toXmlTime + " copy: " + copyTime);
+        }
+        return writeCursor.getDocument();
+    }
+
+    /**
+     * Signs the document and inserts the Signature element according to the
+     * XPath expression (appending the resulting signature). The returned 
+     * document contains the original document with a Signature element either
+     * enveloped or detached, depending on whether the references contain 
+     * the signature.
+     *
+     * @param xpath The XPath expression pointing to a single node that the
+     *        resulting Signature will be appended to. Note that it is an error
+     *        if the xpath expression evaluates to a NodeList (i.e., must be a
+     *        single Node)
+     * @return the document with the signature.
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing 
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node, or if xpath does not evaluate 
+     *  to a single node.
+     */
+    public Document sign(XPath xpath) 
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException, XPathException
+    {
+        return sign(xpath, false);
+    }
+
+    /**
+     * Signs the document and inserts the Signature element according to the
+     * XPath expression. The original document will be returned, amended 
+     * with a Signature element enveloped or detached, depending on whether
+     * the references contain the signature.
+     *
+     * @param xpath The XPath expression pointing to a single node to which the
+     *  resulting Signature will be appended. Note that it is an error if the 
+     *  Xpath expression evaluates to a NodeList (that is, the Xpath 
+     *  expression must evaluate to a single Node).
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing.
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available.
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node, or if xpath does not evaluate 
+     *  to a single node, or if the resulting signature cannot be inserted
+     *  at the position pointed to.
+     */
+    public void signInPlace(XPath xpath) 
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException, XPathException
+    {
+        inPlace = true;
+        sign(xpath, false);
+    }
+
+    /**
+     * Signs the document and inserts the Signature element according to the
+     * XPath expression (appending the resulting signature). The original 
+     * document containsis returned. It will contain a Signature element either
+     * enveloped or detached, depending on whether the references contain 
+     * the signature.
+     *
+     * @param xpath The XPath expression pointing to a single node that the
+     *        resulting Signature will be appended to. Note that it is an error
+     *        if the xpath expression evaluates to a NodeList (i.e., must be a
+     *        single Node)
+     *
+     * @param insertBefore if true, the signature will be inserted before
+     *  the resulting node of the xpath expression; if false, the signature 
+     *  will be appended as a child to the resulting node of the Xpath 
+     *  expression.
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing 
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node, or if xpath does not evaluate 
+     *  to a single node.
+     */
+    public void signInPlace(XPath xpath, boolean insertBefore) 
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException, XPathException
+    {
+        inPlace = true;
+        sign(xpath, insertBefore);
+    }
+
+    /**
+     * Signs the document and inserts the Signature element according to the
+     * XPath expression (appending the resulting signature). The returned 
+     * document contains the original document with a Signature element either
+     * enveloped or detached, depending on whether the references contain 
+     * the signature.
+     *
+     * @param xpath The XPath expression pointing to a single node that the
+     *        resulting Signature will be appended to. Note that it is an error
+     *        if the xpath expression evaluates to a NodeList (i.e., must be a
+     *        single Node)
+     *
+     * @param insertBefore if true, the signature will be inserted before
+     *  the resulting node of the xpath expression; if false, the signature 
+     *  will be appended as a child to the resulting node of the Xpath 
+     *  expression.
+     * @return the document with the signature.
+     *
+     * @throws SignatureException see java.security.Signature.sign()
+     * @throws InvalidKeyException if the key used for signing is not
+     *  usable for signing 
+     * @throws NoSuchAlgorithmException if the RSA signing algorithm is not
+     *  available
+     * @throws XPathException if one of the XPath supplied references 
+     *  does not evaluate to a single node, or if xpath does not evaluate 
+     *  to a single node.
+     */
+    public Document sign(XPath xpath, boolean insertBefore) 
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException, XPathException
+    {
+        boolean doTimes = log.isDebugEnabled();
+        long startTime = 0;
+        if (doTimes){
+            startTime = System.currentTimeMillis();
+        }
+        createWriteCursor();
+        writeCursor.moveToTop();
+        checkXPathExpression(xpath);
+        if (!writeCursor.moveToXPath(xpath)){
+            throw new XPathException("XPath expression '" 
+                                     + xpath.getXPath() + "'"
+                                     + " evaluates to nothing");
+        }
+        int size = refs.size();
+        if (size == 0){
+            XPath xp = new XPath("/");
+            addReference(xp);
+        }
+        Vector targets = new Vector();
+        java.util.Map map = new java.util.Hashtable();
+        size = refs.size();
+        for (int i=0; i < size; ++i){
+            XPath xp = (XPath) refs.elementAt(i);
+            checkXPathExpression(xp);
+
+            DOMCursor c = writeCursor.cloneCursor();
+            if (!c.moveToXPath(xp)){
+                throw new XPathException("XPath expression '" 
+                                         + xp.getXPath() + "'"
+                                     + " evaluates to nothing");
+            }
+            targets.add(c);
+            map.put(c, xp);
+        }
+        SignedInfo signedInfo = signature.getSignedInfo();
+        Enumeration enumer = targets.elements();
+        while (enumer.hasMoreElements()){
+            DOMCursor c = (DOMCursor) enumer.nextElement();
+            Reference r = new Reference();
+            boolean needEnveloped;
+            if (insertBefore) {
+                // use descendent check when inserting before the relative
+                needEnveloped = !c.equals(writeCursor) &&
+                                 c.contains(writeCursor);
+            } else {
+                // use descendent-or-self check when appending under
+                needEnveloped = c.contains(writeCursor);
+            }
+            if (needEnveloped){
+                if (log.isDebugEnabled()){
+                    log.debug("Adding enveloped transform");
+                }
+                r.addTransform(new EnvelopedTransform());
+            }
+            addC14nTransform(r);
+            r.setTarget(c);
+            XPath refXPath = (XPath) map.get(c);
+
+            // output URI="" rather than #xpointer(/) since the former 
+            // is REQUIRED in the spec, and the latter only RECOMMENDed
+            String foo = refXPath.getXPath();
+            if ("/".equals(foo)){
+                foo = "";
+            } else {
+                foo = refXPath.toXPointer();
+            }
+            r.setUri(foo);
+            signedInfo.addReference(r);
+        }
+
+        signedInfo.calculateReferences();
+
+        byte[] canon;
+
+        if (org.apache.tsik.c14n.CanonicalizerFactory.USE_OLD_IMPL) {
+            // Use the DOMCursor to force an empty default namespace
+            // on top of he SignedInfo, so that we can canonicalize
+            // correctly 
+            DOMWriteCursor foo = new DOMWriteCursor();
+            foo.copyUnder(writeCursor);
+            foo = foo.addUnder(null, null, "temp");
+            canon = signedInfo.canonicalize(foo);
+        } else {
+            canon = signedInfo.canonicalize(writeCursor);
+        }
+
+        if (log.isDebugEnabled()){
+            log.debug("canonical form = "+new String(canon));
+        }
+        SigningKey signingKey = signature.getSigningKey();
+
+        byte[] bsig = signingKey.signData(canon);
+        signature.setSignatureValue(bsig);
+
+        if (log.isDebugEnabled()){
+            log.debug("sign="+signature);
+        }
+
+        DOMWriteCursor wc = new DOMWriteCursor();
+        long t = 0;
+        if (doTimes) {
+            t = System.currentTimeMillis();
+        }
+        signature.toXml(wc);
+        long toXmlTime = 0;
+        if (doTimes){
+            toXmlTime = System.currentTimeMillis() - t;
+        }
+        if (insertBefore){
+            writeCursor.copyBefore(wc);
+        } else {
+            writeCursor.copyUnder(wc);
+        }
+        long elapsedTime;
+        if (doTimes){
+            elapsedTime = System.currentTimeMillis()-startTime;
+            log.debug("Time to sign: "+elapsedTime+" ms, of which toXml: "
+                      + toXmlTime);
+        }
+        return writeCursor.getDocument();
+    }
+}

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Signer.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKey.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKey.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKey.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKey.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,52 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SignatureException;
+
+/**
+ * A class implements this interface if it can sign xml messages.
+ */
+public interface SigningKey 
+{
+    /**
+     * Signs the data, returning the signed data.
+     *
+     * @param data the data to sign
+     * @return the signed data
+     * @throws SignatureException 
+     * @throws InvalidKeyException 
+     * @throws NoSuchAlgorithmException
+     */
+    public byte[] signData(byte[] data)
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException;
+
+    /**
+     * Returns the algorithm URI for this signing key. This URI
+     * is typically defined in the XML specification this key is
+     * used in.
+     *
+     * @return the algorithm URI
+     */
+    public String getAlgorithmUri();
+}
+

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKey.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKeyFactory.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKeyFactory.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKeyFactory.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKeyFactory.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,53 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.PrivateKey;
+import java.security.interfaces.DSAPrivateKey;
+import java.security.interfaces.RSAPrivateKey;
+
+/**
+ * TODO javadoc.
+ */
+public class SigningKeyFactory
+{
+    private SigningKeyFactory(){}
+
+    /**
+     * Returns a signing key for the given private key.  Null is returned if
+     * the key value is not an RSAPrivateKey or a DSAPrivateKey.
+     *
+     * @param key TODO.
+     * @return the signing key or null.
+     * @throws GeneralSecurityException TODO.
+     */
+    public static SigningKey makeSigningKey(Key key) 
+        throws GeneralSecurityException
+    {
+        if (key instanceof RSAPrivateKey) {
+            return new RSASigningKey((PrivateKey) key);
+        } else if (key instanceof DSAPrivateKey) {
+            return new DSASigningKey((PrivateKey) key);
+        } else {
+            return null;
+        }
+    }
+}

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/SigningKeyFactory.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Verifier.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Verifier.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Verifier.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Verifier.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,546 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.PublicKey;
+import java.security.SignatureException;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.RSAPublicKey;
+import java.util.Arrays;
+import org.apache.tsik.common.Logger;
+import org.apache.tsik.common.LoggerFactory;
+import org.apache.tsik.domutil.DOMCursor;
+import org.apache.tsik.domutil.elements.ElementException;
+import org.apache.tsik.xmlsig.elements.KeyInfo;
+import org.apache.tsik.xmlsig.elements.KeyValue;
+import org.apache.tsik.xmlsig.elements.Signature;
+import org.apache.tsik.xmlsig.elements.SignedInfo;
+import org.apache.tsik.xpath.XPath;
+import org.apache.tsik.xpath.XPathException;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+
+/**
+ * Verifier verifies XML signatures according to the W3C XML-Signature
+ * specification (<a href="http://www.w3.org/2000/09/xmldsig#">http://www.w3.org/2000/09/xmldsig#</a>). <p>
+ *
+ * A DOM document may contain several signatures. This class can verify
+ * all signatures in a document, one at a time, with either the verification
+ * key supplied in the document, or with a user-supplied key.<p>
+ *
+ * Usage:
+ * <ol>
+ * <li> Construct the Verifier. You must provide the Verifier with 
+ * 1) the XML document that contains the signature and 2) the location of 
+ * the signature within the XML document.  
+ * To provide the location of the signature within an XML document, you 
+ * must use an XPath 
+ * expression. For more on constructing XPaths, see
+ * <a href="http://www.w3.org/TR/xpath">http://www.w3.org/TR/xpath</a>. 
+ *
+ * <li> Supply the verification key. This key may be taken from the document
+ *      (if available) by default, or a specific key may be supplied by the
+ *      user.
+ *
+ * <li> Verify the
+ *      signature. Note that the <code>Verifier</code> will locate and verify 
+ * the signature specified in Step 1.
+ * </ol>
+ * <P>
+ * <b>Note:</b> An XML document may contain several signatures, but this 
+ * API only
+ * supports verification of one signature per <code>Verifier</code>. If 
+ * you need to verify multiple signatures, 
+ * create a new <code>Verifier</code> for each signature.
+ * <p>
+ *
+ * Example use:
+ * <pre>
+ *      String ns[] = {"ds", "http://www.w3.org/2000/09/xmldsig#"};
+ *      XPath signatureLocation = new XPath("//ds:Signature", ns);
+ *      Verifier verifier = new Verifier(doc, signatureLocation);       
+ *      boolean isVerified = verifier.verify();
+ * </pre>
+ *
+ * In the above example, we try to verify the signature by
+ * <code>signatureLocation</code> using the key found within the
+ * signature at <code>signatureLocation</code>. If 
+ * <code>signatureLocation</code> does not contain a single signature, 
+ * an exception is thrown.
+ * To set the key used to verify the signature:
+ * <pre>  
+ *      String ns[] = {"ds", "http://www.w3.org/2000/09/xmldsig#"};
+ *      XPath signatureLocation = new XPath("//ds:Signature", ns);
+ *      Verifier verifier = new Verifier(doc, signatureLocation);       
+ *      RSAPublicKey verifyingKey = [some public key];
+ *      boolean isVerified = verifier.verify(verifyingKey);
+ * </pre>
+ *  
+ */
+
+public class Verifier 
+{
+    private static Logger log = LoggerFactory.getLogger(Verifier.class);
+
+    private DOMCursor cursor;
+    private Signature signature;
+    private byte[] canon;
+    private long canonTime = 0;
+    private long cursorTime = 0;
+    private long moveTime = 0;
+    private long fromXmlTime = 0;
+
+    private VerifyingKey verifyingKey = null;
+
+    /**
+     * Creates a Verifier that points to a single
+     * Signature within the document. 
+     * Verifier uses the key found in the signature element. 
+     *
+     * @param doc the Document. Note that the verifier will not change 
+     *  the input document (so you need not clone it).
+     *
+     * @param signatureLocation an Xpath expression that points to a
+     *  single signature
+     *
+     * @throws IllegalArgumentException if the input is illegal. The 
+     *  exception thrown will indicate wich input is illegal.
+     * @throws XPathException if signatureLocation does not evaluate to
+     *  a single Signature element.
+     * @throws NoSuchAlgorithmException TODO.
+     */
+    public Verifier(Document doc, XPath signatureLocation) 
+        throws XPathException, NoSuchAlgorithmException
+    {
+        boolean doTimes = log.isDebugEnabled();
+        if (doc == null){
+            throw new IllegalArgumentException("document cannot be null");
+        }
+        if (signatureLocation == null){
+            throw new IllegalArgumentException("signature location cannot "
+                                               +"be null");
+        }
+        long t = 0;
+        if (doTimes){ 
+            t = System.currentTimeMillis();
+        }
+        cursor = new DOMCursor(doc);
+        if (doTimes) {
+            cursorTime = System.currentTimeMillis() - t;
+            t = System.currentTimeMillis();
+        }
+
+        cursor = moveCursor(cursor, signatureLocation);
+        if (doTimes){ 
+            moveTime = System.currentTimeMillis() - t;
+        }
+        try {
+            if (doTimes){ 
+                t = System.currentTimeMillis();
+            }
+            signature = Signature.fromXml(cursor);
+            if (doTimes){ 
+                fromXmlTime = System.currentTimeMillis() - t;
+            }
+        } catch (ElementException e){
+            throw new IllegalArgumentException(e.toString());
+        }           
+
+        // save the canonical value of SignedInfo here, since
+        // the enveloped transformation will remove Signature
+        // (and hence SignedInfo)
+        SignedInfo signedInfo = signature.getSignedInfo();
+        if (doTimes){ 
+            t = System.currentTimeMillis();
+        }
+        canon = signedInfo.canonicalizeExisting(cursor);
+        if (doTimes){ 
+            canonTime = System.currentTimeMillis() - t;
+        }
+    }
+
+
+    private DOMCursor moveCursor(DOMCursor cursor, XPath xp) 
+        throws XPathException
+    {
+        if ((!cursor.moveToXPath(xp)) 
+            ||  (!("Signature".equals(cursor.getLocalName())))){
+            throw new XPathException("XPath expression '" 
+                                     + xp.getXPath() + "'"
+                                     + " does not evaluate to " 
+                                     + Signature.uri + ":" 
+                                     + Signature.name);
+        }
+        return cursor;
+    }
+
+
+    /**
+     * Verifies the signature at the previously given signature location.
+     * This is equal to <code>verify(getVerifyingKey())</code>
+     * 
+     * @return true if the signature found according to the XPath 
+     *  expression verifies; false otherwise 
+     *
+     * @throws XPathException if <code>signatureLocation</code> does not 
+     *  evaluate to a
+     *  single node, or if the xpath expression results in zero signatures. 
+     *
+     * @throws InvalidKeyException if
+     *  <ul>
+     *  <li>a valid verifying key cannot be found, or</li> 
+     *  <li>it is not of type <code>RSAPublicKey</code> or 
+     *      <code>DSAPublicKey</code>, or</li>
+     *  <li>for cases where both a key and a certificate is part of the 
+     *      signature's keying information, if the key is not equal to 
+     *      the certificate's key.</li>
+     *  </ul>
+     *
+     * @throws NoSuchAlgorithmException if one of the algorithms inside the
+     *  Signature element is unavailable or not allowed.
+     *
+     * @throws SignatureException see java.security.Signature.verify()
+     */
+    public boolean verify() throws InvalidKeyException, XPathException,
+    NoSuchAlgorithmException, SignatureException
+    {          
+        PublicKey publicKey = getVerifyingKey();
+        if (publicKey == null){
+            throw new InvalidKeyException("No verification key set");
+        }
+        return verify(publicKey);
+    }
+
+    /**
+     * Verifies the signature at the previously given signature location
+     * using the supplied key. Note that all keying information in
+     * the signature being verified is ignored, and the supplied key will
+     * be used.
+     * 
+     * @param pubKey The key used to verify the signature.
+     *
+     * @return true if the signature found according to the XPath 
+     *  expression verifies; false otherwise 
+     *
+     * @throws XPathException if <code>signatureLocation</code> does not 
+     *  evaluate to a
+     *  single node, or if the xpath expression results in zero signatures. 
+     *
+     * @throws InvalidKeyException if
+     *  <ul>
+     *  <li>a valid verifying key is null, or</li> 
+     *  <li>it is not of type RSAPublicKey or DSAPublicKey</li>
+     *  </ul>
+     *
+     * @throws NoSuchAlgorithmException if one of the algorithms inside the
+     *  Signature element is unavailable or not allowed.
+     *
+     * @throws SignatureException see java.security.Signature.verify()
+     */
+    public boolean verify(PublicKey pubKey) throws 
+    InvalidKeyException, XPathException, NoSuchAlgorithmException, 
+    SignatureException
+    {          
+        if (pubKey == null){
+            throw new InvalidKeyException("No verification key set");
+        }
+        this.verifyingKey = createVerifyingKey(pubKey);
+        signature.setVerifyingKey(verifyingKey);
+        return internalVerify();
+    }
+
+    /**
+     * Verifies the signature at the previously given signature location
+     * using the supplied key. Note that all keying information in
+     * the signature being verified is ignored, and the supplied key
+     * will be used.
+     * 
+     * @param verKey The key used to verify the signature.
+     *
+     * @return true if the signature found according to the XPath 
+     *  expression verifies; false otherwise 
+     *
+     * @throws XPathException if <code>signatureLocation</code> does not 
+     *  evaluate to a
+     *  single node, or if the xpath expression results in zero signatures. 
+     *
+     * @throws InvalidKeyException if a verKey is null
+     *
+     * @throws NoSuchAlgorithmException if one of the algorithms inside the
+     *  Signature element is unavailable or not allowed.
+     *
+     * @throws SignatureException see java.security.Signature.verify()
+     */
+    public boolean verify(VerifyingKey verKey) throws 
+        InvalidKeyException, XPathException, NoSuchAlgorithmException, 
+        SignatureException
+    {
+        if (verKey == null){
+            throw new InvalidKeyException("No verification key set");
+        }
+        this.verifyingKey = verKey;
+        signature.setVerifyingKey(verifyingKey);
+        return internalVerify();
+    }
+
+
+    private boolean internalVerify() throws 
+        InvalidKeyException, XPathException, NoSuchAlgorithmException, 
+        SignatureException
+    {   
+        boolean doTimes = log.isDebugEnabled();
+        // give the verifying key the chance to construct internal
+        // keying information from the keyinfo, if there is one
+        DOMCursor c = cursor.cloneCursor();
+        String ns[] = {"ds", "http://www.w3.org/2000/09/xmldsig#"};
+        XPath xp = new XPath("./ds:KeyInfo", ns);
+        if (c.moveToXPath(xp)){
+            verifyingKey.readKeyInfo(c.getElement());
+        }
+
+        SignedInfo signedInfo = signature.getSignedInfo();
+        if (!signedInfo.verifyReferences()){
+            return false;
+        }
+        if (log.isDebugEnabled()){ 
+            log.debug("canonical form = "+new String(canon));
+        }
+        long startTime = 0;
+        if (doTimes){
+            startTime = System.currentTimeMillis();
+        }
+        boolean b = signature.verifySignature(canon);
+        if (doTimes){
+            long elapsedTime = System.currentTimeMillis()-startTime;
+            log.debug("Time to verify: " + (elapsedTime + canonTime 
+                                            + cursorTime + moveTime 
+                                            + fromXmlTime)
+                      +" ms, of which c14n: "+canonTime+" curs:"+cursorTime
+                      +" move: "+moveTime+" fromXml: "+fromXmlTime);
+        }
+        return b;
+    }
+
+
+    /**
+     * Returns whether the element at the given XPath is contained by one of
+     * the Signature references, i.e., whether it is signed.
+     *
+     * @param xpath is the location of the element to check.
+     *
+     * @return whether the element at the given XPath is referenced (signed).
+     */
+    public boolean isReferenced(XPath xpath) 
+    {
+        SignedInfo signedInfo = signature.getSignedInfo();
+        return signedInfo.isReferenced(xpath);
+    }
+
+    /**
+     * Returns all elements referenced by the Signature.
+     * @return all elements referenced by the Signature.
+     */
+    public Element[] getReferencedElements()
+    {
+        SignedInfo signedInfo = signature.getSignedInfo();
+        return signedInfo.getReferencedElements();
+    }
+
+    private VerifyingKey createVerifyingKey(PublicKey verifyingKey)
+        throws InvalidKeyException
+    { 
+        VerifyingKey verKey;
+        if (verifyingKey instanceof RSAPublicKey){
+            verKey = new RSAVerifyingKey(verifyingKey);
+        } else if (verifyingKey instanceof DSAPublicKey){
+            verKey = new DSAVerifyingKey(verifyingKey);
+        } else {
+            throw new IllegalArgumentException("unknown signing key type");
+        }
+        return verKey;
+    }
+
+    /**
+     * Returns the verification key in the document. The verifying
+     * key will be retrieved from the Signature element pointed to by
+     * the xpath supplied in the constructor.
+     *
+     * @return the verifying key found at the xpath expression; null
+     *  if no verifying key can be found, or for cases where both a key 
+     *  and a certificate is part of the signature's keying information, 
+     *  if the key is not equal to the certificate's key.
+     *
+     * @throws InvalidKeyException if the verifying key is not of type 
+     *  <code>RSAPublicKey</code> or <code>DSAPublicKey</code>
+     *
+     * @throws XPathException if <code>xpath</code> results in no 
+     *  usable verifying key (as defined by 
+     *  http://www.w3.org/2000/09/xmldsig:KeyInfo/KeyValue)
+     *
+     * @throws NoSuchAlgorithmException if the RSA algorithm is not
+     *  available
+     */
+    public PublicKey getVerifyingKey() 
+        throws XPathException, InvalidKeyException, NoSuchAlgorithmException
+    {
+        PublicKey publicKey = internalGetVerifyingKey();
+        X509Certificate cert = internalGetCertificate();
+        if (cert == null) {
+            return publicKey;
+        }
+
+        if (compare(cert, publicKey) != null){
+            return publicKey;
+        } else {
+            return null;
+        }
+    }
+
+    
+    private PublicKey internalGetVerifyingKey() 
+        throws XPathException, InvalidKeyException, NoSuchAlgorithmException
+    {
+        KeyInfo keyInfo = signature.getKeyInfo();
+        KeyValue keyValue = keyInfo.getKeyValue();
+        
+        if (keyValue == null){
+            throw new InvalidKeyException("No verifying key available");
+        }
+
+        // interface VerifyingKey does not have a 'getPublicKey()' method
+        // since not all verifying keys are public keys
+        VerifyingKey r = keyValue.generateVerifyingKey();
+        if (r instanceof RSAVerifyingKey){
+            return ((RSAVerifyingKey) r).getPublicKey();
+        } else if (r instanceof DSAVerifyingKey){
+            return ((DSAVerifyingKey) r).getPublicKey();
+        } else {
+            return null;
+        }
+    }
+
+
+    /**
+     * Returns the certificate in the document. If there are multiple
+     * certificates available, only the first (in document order) will be 
+     * returned.
+     *
+     * @return the certificate found at the XPath expression; null if no
+     *  certificate can be found, or if both a key and a certificate is 
+     *  part of the signature's keying information, and the key is not 
+     *  equal to the certificate's key.
+     *
+     * @throws XPathException if <code>xpath</code> results in no 
+     *  usable certificate (as defined by 
+     *  http://www.w3.org/2000/09/xmldsig:KeyInfo/X509Data)
+     */
+    public X509Certificate getCertificate() throws XPathException
+    {
+        PublicKey publicKey = null;
+        try {
+            publicKey = internalGetVerifyingKey();
+        } catch (Exception e) {
+            // TODO
+        } 
+        return compare(internalGetCertificate(), publicKey);
+    }
+
+    /**
+     * Compares a cert and a key to check if the public key inside
+     * the cert is the same as the key.
+     *
+     * @return cert if key or cert is null; null if the key and
+     *  cert's key don't compare; the cert otherwise
+     */
+    private X509Certificate compare(X509Certificate cert, PublicKey publicKey)
+    {
+        if (cert == null || publicKey == null){
+            return cert;
+        }
+        if (!Arrays.equals(publicKey.getEncoded(),
+                           cert.getPublicKey().getEncoded())) {
+            log.warn("Certificate's key differs from key in KeyInfo");
+            return null;
+        }
+        return cert;
+    }
+
+    private X509Certificate internalGetCertificate() throws XPathException
+    {
+        KeyInfo keyInfo = signature.getKeyInfo();
+        return keyInfo.getCertificate();
+    }
+
+    /**
+     * Returns the certificate chain in the document.
+     *
+     * @return the certificate chain found at the xpath expression; null 
+     *  if no certificate chain can be found, or if both a key and at least
+     *  one certificate is part of the signature's keying information, and 
+     *  the key is not equal to the leaf certificate's key. 
+     *  <p>If there is a single  certificate found, a vector of size 1 will 
+     *  be returned.</p>
+     *
+     * @throws XPathException if <code>xpath</code> results in no 
+     *  usable certificate (as defined by 
+     *  http://www.w3.org/2000/09/xmldsig:KeyInfo/X509Data)
+     */
+    public X509Certificate[] getCertificateChain() throws XPathException
+    {
+        KeyInfo keyInfo = signature.getKeyInfo();
+        X509Certificate[] certs = keyInfo.getCertificateChain();
+
+        if (certs == null) {
+            return null;
+        }
+
+        PublicKey publicKey = null;
+        try {
+            publicKey = internalGetVerifyingKey();
+        } catch (Exception e) {
+            // TODO
+        }
+
+        if (compare(certs[0], publicKey) != null){
+            return certs;
+        } else {
+            log.warn("Leaf certificate's key differs from key in KeyInfo");
+            return null;
+        }
+    }
+
+    /**
+     * Returns the key information in the document.
+     *
+     * @return the key information, or null if none is available.
+     */
+    public org.apache.tsik.xmlsig.KeyInfo getKeyInfo()
+    {
+        KeyInfo keyInfo = signature.getKeyInfo();
+        if (keyInfo != null) {
+            return keyInfo.getKeyInfo();
+        } else {
+            return null;
+        }
+    }
+}
+

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/Verifier.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKey.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKey.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKey.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKey.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,73 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.InvalidKeyException;
+import java.security.SignatureException;
+
+import org.w3c.dom.Element;
+
+/**
+ * A class implements this interface if it can verify xml messages.
+ */
+public interface VerifyingKey 
+{
+    /**
+     * Verifies the signed data.
+     *
+     * @param data the signed data to verify
+     * @param signature the signature over data
+     * @return true if the signature verifies; false otherwise
+     * @throws SignatureException 
+     * @throws InvalidKeyException 
+     * @throws NoSuchAlgorithmException
+     */
+    public boolean verifySignature(byte[] data, byte[] signature)
+        throws SignatureException, InvalidKeyException, 
+               NoSuchAlgorithmException;
+
+    /**
+     * Returns the algorithm URI for this signing key. This URI
+     * is typically defined in the XML specification this key is
+     * used in.
+     *
+     * @return the algorithm URI
+     */
+    public String getAlgorithmUri();
+
+    /**
+     * Reads keying information from a &lt;ds:KeyInfo&gt; element.
+     * The implementing class must treat this element as read-only.
+     * 
+     * @param keyInfoElement the &lt;ds:KeyInfo&gt; element
+     */
+    public void readKeyInfo(Element keyInfoElement);
+
+    /**
+     * Writes keying information into a &lt;ds:KeyInfo&gt; element.
+     * The implementing class must ensure the well-formedness and
+     * schema validity of the element is kept.
+     * 
+     * @param keyInfoElement the &lt;ds:KeyInfo&gt; element that
+     *  the elements should be created under
+     */
+    public void writeKeyInfo(Element keyInfoElement);
+}
+

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKey.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKeyFactory.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKeyFactory.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKeyFactory.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKeyFactory.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,102 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig;
+
+import java.security.GeneralSecurityException;
+import java.security.Key;
+import java.security.PublicKey;
+import java.security.cert.X509Certificate;
+import java.security.interfaces.DSAPublicKey;
+import java.security.interfaces.RSAPublicKey;
+
+/**
+ * TODO javadoc.
+ */
+public class VerifyingKeyFactory
+{
+    private VerifyingKeyFactory()
+    {
+    }
+
+    /**
+     * Returns a verifying key for the public key that would be returned by
+     * {@link KeyInfo#getKeyValue}.  Null is returned if the key value is not
+     * an RSAPublicKey or a DSAPublicKey.
+     *
+     * @param keyInfo TODO.
+     * @return the verifying key or null.
+     * @throws GeneralSecurityException TODO.
+     */
+    public static VerifyingKey makeVerifyingKey(KeyInfo keyInfo)
+        throws GeneralSecurityException
+    {
+        X509Certificate[] certs = keyInfo.getCertificateChain();
+        if (certs != null) {
+            return makeVerifyingKey(certs);
+        } else {
+            PublicKey key = keyInfo.getKeyValue();
+            if (key != null) {
+                return makeVerifyingKey(key);
+            } else {
+                return null;
+            }
+        }
+    }
+
+    /**
+     * Returns a verifying key for the given public key .  Null is returned if
+     * the key value is not an RSAPublicKey or a DSAPublicKey.
+     *
+     * @param key TODO.
+     * @return the verifying key or null.
+     * @throws GeneralSecurityException TODO.
+     */
+    public static VerifyingKey makeVerifyingKey(Key key)
+        throws GeneralSecurityException
+    {
+        if (key instanceof RSAPublicKey) {
+            return new RSAVerifyingKey((PublicKey) key);
+        } else if (key instanceof DSAPublicKey) {
+            return new DSAVerifyingKey((PublicKey) key);
+        } else {
+            return null;
+        }
+    }
+
+    /**
+     * Returns a verifying key for the given certificate chain.  Null is
+     * returned if the key value is not an RSAPublicKey or a DSAPublicKey.
+     *
+     * @param certs TODO.
+     * @return the verifying key or null.
+     * @throws GeneralSecurityException TODO.
+     */
+    public static VerifyingKey makeVerifyingKey(X509Certificate[] certs)
+        throws GeneralSecurityException
+    {
+        PublicKey key = certs[0].getPublicKey();
+        if (key instanceof RSAPublicKey) {
+            return new RSAVerifyingKey(certs);
+        } else if (key instanceof DSAPublicKey) {
+            return new DSAVerifyingKey(certs);
+        } else {
+            return null;
+        }
+    }
+}

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/VerifyingKeyFactory.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/CanonicalizationMethod.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/CanonicalizationMethod.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/CanonicalizationMethod.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/CanonicalizationMethod.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,115 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig.elements;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+import org.apache.tsik.c14n.Canonicalizer;
+import org.apache.tsik.c14n.CanonicalizerFactory;
+import org.apache.tsik.common.Logger;
+import org.apache.tsik.common.LoggerFactory;
+import org.apache.tsik.domutil.DOMCursor;
+import org.apache.tsik.domutil.DOMWriteCursor;
+import org.apache.tsik.domutil.elements.ElementImpl;
+import org.apache.tsik.util.Namespaces;
+
+/*
+ <element name="CanonicalizationMethod" type="ds:CanonicalizationMethodType"/> 
+
+ <complexType name="CanonicalizationMethodType" mixed="true">
+   <sequence>
+     <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/>
+     <!-- (0,unbounded) elements from (1,1) namespace -->
+    </sequence>
+    <attribute name="Algorithm" type="anyURI" use="required"/> 
+ </complexType>
+*/
+
+public class CanonicalizationMethod extends ElementImpl
+{
+    private static Logger log 
+	= LoggerFactory.getLogger(CanonicalizationMethod.class);
+
+    protected static String name = "CanonicalizationMethod";
+    protected static String prefix = Namespaces.XMLSIG.getPrefix(); 
+    protected static String uri = Namespaces.XMLSIG.getUri(); 
+    protected static String[] ns = {CanonicalizationMethod.prefix, 
+				    CanonicalizationMethod.uri};
+
+    private String algorithmUri;
+    private List inclusivePrefixList = Collections.EMPTY_LIST;
+
+    protected static String ExclusiveCanonicalizationUri =
+        Canonicalizer.EXCLUSIVE;
+
+    public static String CanonicalizationUri =
+        Canonicalizer.NORMAL;
+
+    public void toXml(DOMWriteCursor wc) 
+    {
+	wc = wc.addUnder(CanonicalizationMethod.uri, 
+			 CanonicalizationMethod.prefix, 
+			 CanonicalizationMethod.name);
+	wc.setAttribute("Algorithm", algorithmUri);
+    }
+
+    public static CanonicalizationMethod fromXml(DOMCursor cursor)
+    {
+	DOMCursor cc 
+	    = CanonicalizationMethod.placeCursor(cursor,
+						 CanonicalizationMethod.name,
+						CanonicalizationMethod.prefix, 
+						 CanonicalizationMethod.uri,
+						 CanonicalizationMethod.ns);
+	
+	String algorithmUri = cc.getAttribute("Algorithm");
+	return new CanonicalizationMethod(algorithmUri);
+    }
+
+    private CanonicalizationMethod(String algorithmUri)
+    {
+	this.algorithmUri = algorithmUri;
+    }
+
+    protected CanonicalizationMethod(String algorithmUri, 
+				     List inclusivePrefixList)
+    {
+	this.algorithmUri = algorithmUri;
+	this.inclusivePrefixList = inclusivePrefixList;
+    }
+
+    protected CanonicalizationMethod()
+    {
+	this.algorithmUri = CanonicalizationMethod.CanonicalizationUri;
+    }
+
+
+    protected byte[] canonicalize(DOMCursor cursor, Map namespaces)
+    {
+        Canonicalizer c = CanonicalizerFactory.getInstance(algorithmUri);
+        c.setInclusivePrefixList(inclusivePrefixList);
+        return c.canonicalize(cursor.getElement(), namespaces);
+    }
+
+    public String toString() 
+    {
+	return "[CanonicalizationMethod " + algorithmUri + "]";
+    }
+}

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/CanonicalizationMethod.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DSAKeyValue.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DSAKeyValue.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DSAKeyValue.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DSAKeyValue.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,295 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig.elements;
+
+import java.math.BigInteger;
+import java.security.KeyFactory;
+import java.security.NoSuchAlgorithmException;
+import java.security.interfaces.DSAParams;
+import java.security.interfaces.DSAPrivateKey;
+import java.security.interfaces.DSAPublicKey;
+import java.security.spec.DSAPrivateKeySpec;
+import java.security.spec.DSAPublicKeySpec;
+import java.security.spec.InvalidKeySpecException;
+import org.apache.tsik.datatypes.Base64;
+import org.apache.tsik.domutil.DOMCursor;
+import org.apache.tsik.domutil.DOMWriteCursor;
+import org.apache.tsik.domutil.elements.ElementImpl;
+import org.apache.tsik.util.Namespaces;
+
+/*
+  <element name="DSAKeyValue" type="ds:DSAKeyValueType"/> 
+  <complexType name="DSAKeyValueType"> 
+    <sequence>
+      <sequence minOccurs="0">
+        <element name="P" type="ds:CryptoBinary"/> 
+        <element name="Q" type="ds:CryptoBinary"/>
+      </sequence>
+      <element name="J" type="ds:CryptoBinary" minOccurs="0"/>
+      <element name="G" type="ds:CryptoBinary" minOccurs="0"/> 
+      <element name="Y" type="ds:CryptoBinary"/> 
+      <sequence minOccurs="0">
+        <element name="Seed" type="ds:CryptoBinary"/> 
+        <element name="PgenCounter" type="ds:CryptoBinary"/> 
+      </sequence>
+    </sequence>
+  </complexType>
+*/
+
+public class DSAKeyValue extends ElementImpl
+{
+    protected static String name = "DSAKeyValue";
+    protected static String prefix = Namespaces.XMLSIG.getPrefix(); 
+    protected static String uri = Namespaces.XMLSIG.getUri(); 
+    protected static String[] ns = {DSAKeyValue.prefix, DSAKeyValue.uri};
+
+    private static boolean DEBUG = false;
+
+    private String p = null;
+    private String q = null;
+    private String j = null;
+    private String g = null;
+    private String y = null;
+    private String x = null;
+    private String seed = null;
+    private String pGenCounter = null;
+
+    private DSAKeyValue(String p, String q, String j, String g,
+			String y, String seed, String pGenCounter,
+			String x)
+    {
+	this.p = p;
+	this.q = q;
+	this.j = j;
+	this.g = g;
+	this.y = y;
+	this.x = x;
+	this.seed = seed;
+	this.pGenCounter = pGenCounter;
+    }
+
+    public static boolean isAnElementIn(DOMCursor cursor)
+    {
+	try {
+	    DOMCursor c = placeCursor(cursor, name, prefix, uri, ns);
+	    return true;
+	} catch (IllegalArgumentException e) {
+	    return false;
+	}
+    }
+
+    private byte[] fix2Complement(byte[] a){
+	if (a[0] == 0){
+	    byte[] b = new byte[a.length - 1];
+	    System.arraycopy(a, 1, b, 0, a.length - 1);
+	    return b;
+	}
+	return a;
+    }
+
+    public DSAPublicKey generateDsaPublicKey() 
+	throws NoSuchAlgorithmException, InvalidKeySpecException 
+    {
+        BigInteger Y, P, Q, G;
+
+      	Y = new BigInteger(1, fix2Complement(Base64.decode(y)));
+      	P = new BigInteger(1, fix2Complement(Base64.decode(p)));
+      	Q = new BigInteger(1, fix2Complement(Base64.decode(q)));
+      	G = new BigInteger(1, fix2Complement(Base64.decode(g)));
+
+        KeyFactory dsaKeyFactory = KeyFactory.getInstance("dsa");
+        DSAPublicKeySpec kspec = new DSAPublicKeySpec(Y, P, Q, G);
+        return (DSAPublicKey) dsaKeyFactory.generatePublic(kspec);
+    }
+
+    public DSAPrivateKey generateDsaPrivateKey() 
+	throws NoSuchAlgorithmException, InvalidKeySpecException 
+    {
+        BigInteger X, P, Q, G;
+
+      	X = new BigInteger(1, fix2Complement(Base64.decode(x)));
+      	P = new BigInteger(1, fix2Complement(Base64.decode(p)));
+      	Q = new BigInteger(1, fix2Complement(Base64.decode(q)));
+      	G = new BigInteger(1, fix2Complement(Base64.decode(g)));
+
+        KeyFactory dsaKeyFactory = KeyFactory.getInstance("dsa");
+        DSAPrivateKeySpec kspec = new DSAPrivateKeySpec(X, P, Q, G);
+        return (DSAPrivateKey) dsaKeyFactory.generatePrivate(kspec);
+    }
+
+    public DSAKeyValue(DSAPublicKey key)
+    {
+	DSAParams params = key.getParams();
+	
+	byte[] b = params.getG().toByteArray();
+    	b = fix2Complement(b);
+	g = Base64.encode(b);
+
+	b = params.getP().toByteArray();
+    	b = fix2Complement(b);
+	p = Base64.encode(b);
+
+	b = params.getQ().toByteArray();
+    	b = fix2Complement(b);
+	q = Base64.encode(b);
+
+	b = key.getY().toByteArray();
+    	b = fix2Complement(b);
+	y = Base64.encode(b);
+    }
+
+    public DSAKeyValue(DSAPrivateKey key)
+    {
+	DSAParams params = key.getParams();
+	
+	byte[] b = params.getG().toByteArray();
+    	b = fix2Complement(b);
+	g = Base64.encode(b);
+
+	b = params.getP().toByteArray();
+    	b = fix2Complement(b);
+	p = Base64.encode(b);
+
+	b = params.getQ().toByteArray();
+    	b = fix2Complement(b);
+	q = Base64.encode(b);
+
+	b = key.getX().toByteArray();
+    	b = fix2Complement(b);
+	x = Base64.encode(b);
+    }
+
+
+    public String toString() 
+    {
+	String s = "[DSAKeyValue";
+
+	if (p != null) s += " p=" + p;
+	if (q != null) s += " q=" + q;
+	if (j != null) s += " j=" + j;
+	if (g != null) s += " g=" + g;
+	if (y != null) s += " y=" + y;
+	if (x != null) s += " y=" + x;
+	if (seed != null) s += " seed=" + seed;
+	if (pGenCounter != null) s += " pGenCounter=" + pGenCounter;
+
+	return s + "]";
+    }
+
+    public void toXml(DOMWriteCursor wc)
+    {
+	wc = wc.addUnder(DSAKeyValue.uri, 
+			 DSAKeyValue.prefix, DSAKeyValue.name);
+
+	DOMWriteCursor c;
+	if (p != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "P");
+	    c.setText(p);
+	}
+	if (q != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "Q");
+	    c.setText(q);
+	}
+	if (j != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "J");
+	    c.setText(j);
+	}
+	if (g != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "G");
+	    c.setText(g);
+	}
+	if (y != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "Y");
+	    c.setText(y);
+	}
+	if (x != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "X");
+	    c.setText(x);
+	}
+
+	if (seed != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, "Seed");
+	    c.setText(seed);
+	}
+
+	if (pGenCounter != null) {
+	    c = wc.addUnder(DSAKeyValue.uri, DSAKeyValue.prefix, 
+			    "PgenCounter");
+	    c.setText(pGenCounter);
+	}
+    }
+
+    public static DSAKeyValue fromXml(DOMCursor cursor)
+    { 
+	DOMCursor cc = placeCursor(cursor, name, prefix, uri, ns);
+
+	String p = null;
+	String q = null;
+	String j = null;
+	String g = null;
+	String y = null;
+	String x = null;
+	String seed = null;
+	String pGenCounter = null;
+
+	DOMCursor c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "P")){
+	    p = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "Q")){
+	    q = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "J")){
+	    j = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "G")){
+	    g = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "Y")){
+	    y = c.getText();
+	}
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "X")){
+	    x = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "Seed")){
+	    seed = c.getText();
+	}
+
+	c = cc.cloneCursor();
+	if (c.moveToChild(DSAKeyValue.uri, "PgenCounter")){
+	    pGenCounter = c.getText();
+	}
+	
+	return new DSAKeyValue(p, q, j, g, y, seed, pGenCounter, x);
+    }
+}
+
+
+

Propchange: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DSAKeyValue.java
------------------------------------------------------------------------------
    svn:executable = 

Added: incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DigestMethod.java
URL: http://svn.apache.org/viewcvs/incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DigestMethod.java?rev=230871&view=auto
==============================================================================
--- incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DigestMethod.java (added)
+++ incubator/tsik/trunk/src/org/apache/tsik/xmlsig/elements/DigestMethod.java Mon Aug  8 12:58:58 2005
@@ -0,0 +1,75 @@
+// $Id$
+
+//
+// (C) Copyright 2005 VeriSign, Inc.  All Rights Reserved.
+//
+// VeriSign, Inc. shall have no responsibility, financial or
+// otherwise, for any consequences arising out of the use of
+// this material. The program material is provided on an "AS IS"
+// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
+// express or implied. The user is responsible for determining
+// any necessary third party rights or authorizations that may
+// be required for the use of the materials. Users are advised 
+// that they may need authorizations under certain patents from 
+// Microsoft and IBM, or others. Please see notice.txt file. 
+// VeriSign disclaims any obligation to notify the user of any 
+// such third party rights.
+//
+
+package org.apache.tsik.xmlsig.elements;
+
+import org.apache.tsik.domutil.DOMCursor;
+import org.apache.tsik.domutil.DOMWriteCursor;
+import org.apache.tsik.domutil.elements.ElementImpl;
+import org.apache.tsik.util.Namespaces;
+
+/*
+  <element name="DigestMethod" type="ds:DigestMethodType"/>
+
+  <complexType name="DigestMethodType" mixed="true"> 
+    <sequence>
+      <any namespace="##other" processContents="lax" minOccurs="0" 
+       maxOccurs="unbounded"/>
+    </sequence>    
+    <attribute name="Algorithm" type="anyURI" use="required"/> 
+  </complexType>
+*/
+
+public abstract class DigestMethod extends ElementImpl
+{
+    protected static String name = "DigestMethod";
+    protected static String prefix = Namespaces.XMLSIG.getPrefix(); 
+    protected static String uri = Namespaces.XMLSIG.getUri(); 
+    protected static String[] ns = {DigestMethod.prefix, 
+				    DigestMethod.uri};
+
+    private static boolean DEBUG = false;
+
+    public static String algorithmUri;
+
+    public void toXml(DOMWriteCursor wc) {
+	wc = wc.addUnder(DigestMethod.uri, 
+			 DigestMethod.prefix, DigestMethod.name);
+	wc.setAttribute("Algorithm", algorithmUri);
+    }
+
+    public static DigestMethod fromXml(DOMCursor cursor){
+	DOMCursor cc = DigestMethod.placeCursor(cursor,
+						DigestMethod.name,
+						DigestMethod.prefix, 
+						DigestMethod.uri,
+						DigestMethod.ns);
+
+
+	String algorithmUriString = cc.getAttribute("Algorithm");
+	return DigestMethodFactory.createDigestMethod(algorithmUriString);
+    }
+    
+    protected DigestMethod(String algorithmUri){
+	this.algorithmUri = algorithmUri;
+    }
+
+    protected DigestMethod(){}
+
+    abstract public byte[] digest(byte[] b);
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: tsik-dev-unsubscribe@ws.apache.org
For additional commands, e-mail: tsik-dev-help@ws.apache.org