View | Details | Raw Unified | Return to bug 32657
Collapse All | Expand All

(-)src/org/apache/xml/security/algorithms/Algorithm.java (+4 lines)
Lines 58-63 Link Here
58
           throws XMLSecurityException {
58
           throws XMLSecurityException {
59
      super(element, BaseURI);
59
      super(element, BaseURI);
60
   }
60
   }
61
   
62
   protected Algorithm() {
63
    
64
   };
61
65
62
   /**
66
   /**
63
    * Method getAlgorithmURI
67
    * Method getAlgorithmURI
(-)src/org/apache/xml/security/algorithms/SignatureAlgorithm.java (+36 lines)
Lines 163-168 Link Here
163
                                         ex);
163
                                         ex);
164
      }
164
      }
165
   }
165
   }
166
   public SignatureAlgorithm(String algorithm) throws XMLSecurityException {
167
    
168
    try {
169
        String implementingClass =
170
           SignatureAlgorithm.getImplementingClass(algorithm);
171
        if (log.isDebugEnabled())
172
            log.debug("Create URI \"" + algorithm + "\" class \""
173
                  + implementingClass + "\"");
174
175
        this._signatureAlgorithm =
176
           (SignatureAlgorithmSpi) Class.forName(implementingClass)
177
              .newInstance();
178
179
180
     } catch (ClassNotFoundException ex) {
181
        Object exArgs[] = { algorithm, ex.getMessage() };
182
183
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
184
                                        ex);
185
     } catch (IllegalAccessException ex) {
186
        Object exArgs[] = { algorithm, ex.getMessage() };
187
188
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
189
                                        ex);
190
     } catch (InstantiationException ex) {
191
        Object exArgs[] = { algorithm, ex.getMessage() };
192
193
        throw new XMLSignatureException("algorithms.NoSuchAlgorithm", exArgs,
194
                                        ex);
195
     } catch (NullPointerException ex) {
196
        Object exArgs[] = { algorithm, ex.getMessage() };
197
198
        throw new RuntimeException("algorithms.NoSuchAlgorithm", 
199
                                        ex);
200
     }
201
   }
166
202
167
   /**
203
   /**
168
    * Proxy method for {@link java.security.Signature#sign()}
204
    * Proxy method for {@link java.security.Signature#sign()}
(-)src/org/apache/xml/security/c14n/implementations/Canonicalizer20010315.java (-4 / +4 lines)
Lines 97-103 Link Here
97
         	continue;
97
         	continue;
98
         }
98
         }
99
         
99
         
100
         Node n=ns.addMappingAndRender(NName,NValue,N);          		 
100
         Node n=(Node)ns.addMappingAndRender(NName,NValue,N);          		 
101
		 	 
101
		 	 
102
      	  if (n!=null) {
102
      	  if (n!=null) {
103
      	  	 //Render the ns definition
103
      	  	 //Render the ns definition
Lines 227-233 Link Here
227
       //ns.addInclusiveMapping(NName,NValue,N,isRealVisible);          
227
       //ns.addInclusiveMapping(NName,NValue,N,isRealVisible);          
228
	    if  (this._xpathNodeSet.contains(N))  {
228
	    if  (this._xpathNodeSet.contains(N))  {
229
			    //The xpath select this node output it if needed.
229
			    //The xpath select this node output it if needed.
230
	    		Node n=ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); 	    		
230
	    		Node n=(Node)ns.addMappingAndRenderXNodeSet(NName,NValue,N,isRealVisible); 	    		
231
		 	 	if (n!=null) {
231
		 	 	if (n!=null) {
232
		 	 		result.add(n);
232
		 	 		result.add(n);
233
                    if (C14nHelper.namespaceIsRelative(N)) {
233
                    if (C14nHelper.namespaceIsRelative(N)) {
Lines 244-254 Link Here
244
        Node n=null;
244
        Node n=null;
245
        if (xmlns == null) {
245
        if (xmlns == null) {
246
        	//No xmlns def just get the already defined.
246
        	//No xmlns def just get the already defined.
247
        	n=ns.getMapping(XMLNS);        		
247
        	n=(Node)ns.getMapping(XMLNS);        		
248
        } else if ( !this._xpathNodeSet.contains(xmlns)) {
248
        } else if ( !this._xpathNodeSet.contains(xmlns)) {
249
        	//There is a definition but the xmlns is not selected by the xpath.
249
        	//There is a definition but the xmlns is not selected by the xpath.
250
        	//then xmlns=""
250
        	//then xmlns=""
251
        	n=ns.addMappingAndRenderXNodeSet(XMLNS,"",nullNode,true);        	    		      	
251
        	n=(Node)ns.addMappingAndRenderXNodeSet(XMLNS,"",nullNode,true);        	    		      	
252
        }
252
        }
253
        //output the xmlns def if needed.
253
        //output the xmlns def if needed.
254
        if (n!=null) {
254
        if (n!=null) {
(-)src/org/apache/xml/security/c14n/implementations/Canonicalizer20010315Excl.java (-3 / +3 lines)
Lines 166-172 Link Here
166
		Iterator it=visiblyUtilized.iterator();
166
		Iterator it=visiblyUtilized.iterator();
167
		while (it.hasNext()) {
167
		while (it.hasNext()) {
168
			String s=(String)it.next();									
168
			String s=(String)it.next();									
169
			Attr key=ns.getMapping(s);
169
			Attr key=(Attr)ns.getMapping(s);
170
			if (key==null) {
170
			if (key==null) {
171
				continue;
171
				continue;
172
			}
172
			}
Lines 283-289 Link Here
283
			Iterator it=visiblyUtilized.iterator();
283
			Iterator it=visiblyUtilized.iterator();
284
			while (it.hasNext()) {
284
			while (it.hasNext()) {
285
				String s=(String)it.next();										
285
				String s=(String)it.next();										
286
				Attr key=ns.getMapping(s);
286
				Attr key=(Attr)ns.getMapping(s);
287
				if (key==null) {
287
				if (key==null) {
288
					continue;
288
					continue;
289
				}
289
				}
Lines 293-299 Link Here
293
			Iterator it=this._inclusiveNSSet.iterator();
293
			Iterator it=this._inclusiveNSSet.iterator();
294
			while (it.hasNext()) {
294
			while (it.hasNext()) {
295
				String s=(String)it.next();				
295
				String s=(String)it.next();				
296
				Attr key=ns.getMappingWithoutRendered(s);
296
				Attr key=(Attr)ns.getMappingWithoutRendered(s);
297
				if (key==null) {
297
				if (key==null) {
298
					continue;
298
					continue;
299
				}
299
				}
(-)src/org/apache/xml/security/c14n/implementations/CanonicalizerBase.java (-1 / +1 lines)
Lines 443-449 Link Here
443
   		 }   			
443
   		 }   			
444
   		}
444
   		}
445
        Attr nsprefix;
445
        Attr nsprefix;
446
        if (((nsprefix=ns.getMappingWithoutRendered("xmlns"))!=null) 
446
        if (((nsprefix=(Attr)ns.getMappingWithoutRendered("xmlns"))!=null) 
447
                && "".equals(nsprefix.getValue())) {
447
                && "".equals(nsprefix.getValue())) {
448
             ns.addMappingAndRender("xmlns","",nullNode);
448
             ns.addMappingAndRender("xmlns","",nullNode);
449
        }
449
        }
(-)src/org/apache/xml/security/c14n/implementations/NameSpaceSymbTable.java (-9 / +24 lines)
Lines 72-77 Link Here
72
	   		}
72
	   		}
73
	   }	   
73
	   }	   
74
	}
74
	}
75
    
76
    public  void getUnrenderedNodesNon(Collection result) {        
77
           //List result=new ArrayList();
78
           Iterator it=symb.entrySet().iterator();
79
           while (it.hasNext()) {          
80
                NameSpaceSymbEntry n=(NameSpaceSymbEntry)((Map.Entry)it.next()).getValue();
81
                //put them rendered?
82
                if ((!n.rendered) && (n.n!=null)) {
83
                    result.add(n.n);                    
84
                }
85
           }       
86
        }
75
	
87
	
76
	/**
88
	/**
77
     * Push a frame for visible namespace. 
89
     * Push a frame for visible namespace. 
Lines 125-132 Link Here
125
	}
137
	}
126
	
138
	
127
	final void needsClone() {
139
	final void needsClone() {
128
		if (!cloned) {
140
		if (!cloned ) {
129
            level.remove(level.size()-1);
141
            int num=level.size()-1;
142
            if (num<0)
143
                return;
144
            level.remove(num);
130
            level.add(symb);
145
            level.add(symb);
131
			symb=(HashMap) symb.clone();
146
			symb=(HashMap) symb.clone();
132
            cloned=true;
147
            cloned=true;
Lines 140-146 Link Here
140
     * @return null if there is no need to render the prefix. Otherwise the node of
155
     * @return null if there is no need to render the prefix. Otherwise the node of
141
     * definition.
156
     * definition.
142
     **/
157
     **/
143
	public Attr getMapping(String prefix) {					
158
	public Object getMapping(String prefix) {					
144
		NameSpaceSymbEntry entry=(NameSpaceSymbEntry) symb.get(prefix);
159
		NameSpaceSymbEntry entry=(NameSpaceSymbEntry) symb.get(prefix);
145
		if (entry==null) {
160
		if (entry==null) {
146
			//There is no definition for the prefix(a bug?).
161
			//There is no definition for the prefix(a bug?).
Lines 167-173 Link Here
167
     * @param prefix The prefix whose definition is neaded.
182
     * @param prefix The prefix whose definition is neaded.
168
     * @return the attr to render, null if there is no need to render
183
     * @return the attr to render, null if there is no need to render
169
     **/
184
     **/
170
	public Attr getMappingWithoutRendered(String prefix) {					
185
	public Object getMappingWithoutRendered(String prefix) {					
171
		NameSpaceSymbEntry entry=(NameSpaceSymbEntry) symb.get(prefix);
186
		NameSpaceSymbEntry entry=(NameSpaceSymbEntry) symb.get(prefix);
172
		if (entry==null) {		   
187
		if (entry==null) {		   
173
			return null;
188
			return null;
Lines 185-191 Link Here
185
     * @param n the attribute that have the definition
200
     * @param n the attribute that have the definition
186
     * @return true if there is already defined.
201
     * @return true if there is already defined.
187
     **/
202
     **/
188
	public boolean addMapping(String prefix, String uri,Attr n) {						
203
	public boolean addMapping(String prefix, String uri,Object n) {						
189
		NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);		
204
		NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);		
190
		if ((ob!=null) && uri.equals(ob.uri)) {
205
		if ((ob!=null) && uri.equals(ob.uri)) {
191
			//If we have it previously defined. Don't keep working.
206
			//If we have it previously defined. Don't keep working.
Lines 215-221 Link Here
215
     * @param n the attribute that have the definition
230
     * @param n the attribute that have the definition
216
     * @return the attr to render, null if there is no need to render
231
     * @return the attr to render, null if there is no need to render
217
     **/
232
     **/
218
    public Node addMappingAndRender(String prefix, String uri,Attr n) {                     
233
    public Object addMappingAndRender(String prefix, String uri,Attr n) {                     
219
        NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);
234
        NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);
220
        
235
        
221
        if ((ob!=null) && uri.equals(ob.uri)) {
236
        if ((ob!=null) && uri.equals(ob.uri)) {
Lines 254-260 Link Here
254
     * @return null if there is no need to render the prefix. Otherwise the node of
269
     * @return null if there is no need to render the prefix. Otherwise the node of
255
     * definition.     
270
     * definition.     
256
     **/
271
     **/
257
	public Node addMappingAndRenderXNodeSet(String prefix, String uri,Attr n,boolean outputNode) {						
272
	public Object addMappingAndRenderXNodeSet(String prefix, String uri,Attr n,boolean outputNode) {						
258
		NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);
273
		NameSpaceSymbEntry ob = (NameSpaceSymbEntry)symb.get(prefix);
259
		int visibleNameSpaces=nameSpaces;		
274
		int visibleNameSpaces=nameSpaces;		
260
		if ((ob!=null) && uri.equals(ob.uri)) {
275
		if ((ob!=null) && uri.equals(ob.uri)) {
Lines 297-303 Link Here
297
 * The internal structure of NameSpaceSymbTable.
312
 * The internal structure of NameSpaceSymbTable.
298
 **/
313
 **/
299
class NameSpaceSymbEntry implements Cloneable {
314
class NameSpaceSymbEntry implements Cloneable {
300
    NameSpaceSymbEntry(String name,Attr n,boolean rendered) {
315
    NameSpaceSymbEntry(String name,Object n,boolean rendered) {
301
        this.uri=name;          
316
        this.uri=name;          
302
        this.rendered=rendered;
317
        this.rendered=rendered;
303
        this.n=n;            
318
        this.n=n;            
Lines 319-323 Link Here
319
    /**This prefix-URI has been already render or not.*/
334
    /**This prefix-URI has been already render or not.*/
320
    boolean rendered=false;
335
    boolean rendered=false;
321
    /**The attribute to include.*/
336
    /**The attribute to include.*/
322
    Attr n;        
337
    Object n;        
323
};
338
};
(-)src/org/apache/xml/security/signature/Reference.java (-1 / +1 lines)
Lines 689-695 Link Here
689
         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
689
         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
690
690
691
         mda.reset();
691
         mda.reset();
692
         DigesterOutputStream diOs=new DigesterOutputStream(mda);
692
         DigesterOutputStream diOs=new DigesterOutputStream(mda.getAlgorithm());
693
         OutputStream os=new BufferedOutputStream(diOs);
693
         OutputStream os=new BufferedOutputStream(diOs);
694
         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);         
694
         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);         
695
         output.updateOutputStream(os);
695
         output.updateOutputStream(os);
(-)src/org/apache/xml/security/utils/DigesterOutputStream.java (-2 / +3 lines)
Lines 17-22 Link Here
17
package org.apache.xml.security.utils;
17
package org.apache.xml.security.utils;
18
18
19
import java.io.ByteArrayOutputStream;
19
import java.io.ByteArrayOutputStream;
20
import java.security.MessageDigest;
20
21
21
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
22
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
22
23
Lines 26-36 Link Here
26
 */
27
 */
27
public class DigesterOutputStream extends ByteArrayOutputStream {
28
public class DigesterOutputStream extends ByteArrayOutputStream {
28
    final static byte none[]="error".getBytes();
29
    final static byte none[]="error".getBytes();
29
    final MessageDigestAlgorithm mda;
30
    final MessageDigest mda;
30
	/**
31
	/**
31
	 * @param mda
32
	 * @param mda
32
	 */
33
	 */
33
	public DigesterOutputStream(MessageDigestAlgorithm mda) {
34
	public DigesterOutputStream(MessageDigest mda) {
34
        this.mda=mda;		
35
        this.mda=mda;		
35
	}
36
	}
36
37
(-)src/org/apache/xml/security/utils/SignerOutputStream.java (-2 / +9 lines)
Lines 46-52 Link Here
46
        try {
46
        try {
47
			sa.update(arg0);
47
			sa.update(arg0);
48
		} catch (XMLSignatureException e) {
48
		} catch (XMLSignatureException e) {
49
            throw new RuntimeException(""+e);
49
            throw new RuntimeException("",e);
50
		}
50
		}
51
    }
51
    }
52
    
52
    
Lines 66-72 Link Here
66
            sa.update(arg0,arg1,arg2);
66
            sa.update(arg0,arg1,arg2);
67
        } catch (XMLSignatureException e) {
67
        } catch (XMLSignatureException e) {
68
            throw new RuntimeException(""+e);
68
            throw new RuntimeException(""+e);
69
        }
69
        }        
70
    }
71
    public boolean verify(byte []a) {
72
      try {
73
		return sa.verify(a);
74
	} catch (XMLSignatureException e) {
75
		throw new RuntimeException(""+e);
76
	}  
70
    }
77
    }
71
    
78
    
72
79
(-)src_unitTests/org/apache/xml/security/test/encryption/BaltimoreEncTest.java (-2 / +6 lines)
Lines 21-26 Link Here
21
import java.security.KeyFactory;
21
import java.security.KeyFactory;
22
import java.security.NoSuchAlgorithmException;
22
import java.security.NoSuchAlgorithmException;
23
import java.security.PrivateKey;
23
import java.security.PrivateKey;
24
import java.security.Provider;
24
import java.security.cert.X509Certificate;
25
import java.security.cert.X509Certificate;
25
import java.security.spec.PKCS8EncodedKeySpec;
26
import java.security.spec.PKCS8EncodedKeySpec;
26
27
Lines 184-194 Link Here
184
		haveISOPadding = false;
185
		haveISOPadding = false;
185
		String algorithmId = 
186
		String algorithmId = 
186
			JCEMapper.translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
187
			JCEMapper.translateURItoJCEID(org.apache.xml.security.utils.EncryptionConstants.ALGO_ID_BLOCKCIPHER_AES128);
187
188
		
189
        System.out.println("URItoJCEID:"+algorithmId);
188
		if (algorithmId != null) {
190
		if (algorithmId != null) {
189
			try {
191
			try {
190
				if (Cipher.getInstance(algorithmId) != null)
192
                
193
				if (Cipher.getInstance(algorithmId,"SunJCE") != null)
191
					haveISOPadding = true;
194
					haveISOPadding = true;
195
                
192
			} catch (NoSuchAlgorithmException nsae) {
196
			} catch (NoSuchAlgorithmException nsae) {
193
			} catch (NoSuchPaddingException nspe) {
197
			} catch (NoSuchPaddingException nspe) {
194
			}
198
			}
(-)src_samples/prb/SaxCanon.java (+402 lines)
Added Link Here
1
package prb;
2
import java.io.ByteArrayInputStream;
3
import java.io.ByteArrayOutputStream;
4
import java.io.FileNotFoundException;
5
import java.io.IOException;
6
import java.io.OutputStream;
7
import java.security.MessageDigest;
8
import java.util.ArrayList;
9
import java.util.Iterator;
10
import java.util.List;
11
import java.util.SortedSet;
12
import java.util.TreeSet;
13
14
import javax.xml.parsers.DocumentBuilder;
15
import javax.xml.parsers.DocumentBuilderFactory;
16
import javax.xml.parsers.ParserConfigurationException;
17
import javax.xml.parsers.SAXParser;
18
import javax.xml.parsers.SAXParserFactory;
19
import javax.xml.transform.TransformerException;
20
21
import org.apache.xerces.dom.AttrImpl;
22
import org.apache.xml.security.Init;
23
import org.apache.xml.security.c14n.CanonicalizationException;
24
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
25
import org.apache.xml.security.c14n.implementations.Canonicalizer20010315Excl;
26
import org.apache.xml.security.c14n.implementations.Canonicalizer20010315ExclWithComments;
27
import org.apache.xml.security.c14n.implementations.NameSpaceSymbTable;
28
import org.apache.xml.security.exceptions.XMLSecurityException;
29
import org.apache.xml.security.signature.XMLSignatureException;
30
import org.apache.xml.security.utils.Base64;
31
import org.apache.xml.security.utils.Constants;
32
import org.apache.xml.security.utils.DigesterOutputStream;
33
import org.apache.xml.security.utils.JavaUtils;
34
import org.apache.xml.security.utils.SignerOutputStream;
35
import org.apache.xml.security.utils.XMLUtils;
36
import org.apache.xpath.XPathAPI;
37
import org.w3c.dom.Attr;
38
import org.w3c.dom.Document;
39
import org.w3c.dom.Node;
40
import org.w3c.dom.NodeList;
41
import org.xml.sax.Attributes;
42
import org.xml.sax.SAXException;
43
import org.xml.sax.ext.LexicalHandler;
44
import org.xml.sax.helpers.DefaultHandler;
45
46
/*
47
 * Created on Oct 18, 2004
48
 *
49
 * TODO To change the template for this generated file go to
50
 * Window - Preferences - Java - Code Style - Code Templates
51
 */
52
53
/**
54
 * @author raul
55
 *
56
 * TODO To change the template for this generated type comment go to
57
 * Window - Preferences - Java - Code Style - Code Templates
58
 */
59
public abstract class SaxCanon extends DefaultHandler implements LexicalHandler{
60
	NameSpaceSymbTable ns=new NameSpaceSymbTable();
61
62
	private boolean outputComments=true;
63
   OutputStream os=new ByteArrayOutputStream();
64
	/**
65
	 * 
66
	 */
67
	public SaxCanon()  {        
68
		// TODO Auto-generated constructor stub
69
	}
70
    
71
	/** @throws IOException
72
	 * @inheritDoc **/
73
    final static byte[] EQ_Q= {'=','"'};
74
    final static byte[] END_T= {'<','/'};
75
	public void startElement(String arg0, String arg1, String arg2, Attributes arg3)
76
		throws SAXException {                
77
        ns.push();
78
        SortedSet s = handleAttributes(arg2, arg3);
79
        try {
80
        os.write('<');
81
        writeStringToUtf8(arg2,os);
82
        Iterator it=s.iterator();
83
        while (it.hasNext()) {
84
            String[] attr=(String[])it.next();
85
            os.write(' ');writeStringToUtf8(attr[2],os);
86
            os.write(EQ_Q);
87
            writeStringToUtf8(attr[1],os);
88
            os.write('"');
89
        }
90
        os.write('>');
91
        } catch (IOException e) {
92
        	throw new RuntimeException(e);
93
        }
94
	}
95
    abstract SortedSet handleAttributes(String arg2, Attributes arg3);
96
    /** @inheritDoc **/
97
	public void characters(char[] arg0, int arg1, int arg2) {
98
        try {
99
            for (int i=arg1;i<arg1+arg2;i++)       
100
            	writeCharToUtf8(arg0[i],os);
101
		} catch (IOException e) { 
102
			throw new RuntimeException(e);
103
		}
104
	}
105
    
106
    /** @inheritDoc **/
107
	public void startPrefixMapping(String arg0, String arg1)
108
			throws SAXException {        
109
        String prefix=("".equals(arg0) ? "xmlns" : arg0);
110
        String []attr = {"xmlns"
111
                ,arg1,("".equals(arg0) ? "xmlns" : "xmlns:"+arg0)};
112
        ns.addMapping(prefix,arg1,attr);
113
	}
114
    
115
    /** @inheritDoc **/
116
	public void endElement(String arg0, String arg1, String arg2)
117
			throws SAXException {
118
        try {
119
        os.write(END_T);
120
        writeStringToUtf8(arg2,os);
121
        os.write('>');
122
        } catch (IOException e) {
123
            throw new RuntimeException(e);   
124
        }
125
        ns.pop();
126
127
	}
128
    
129
    /**@param args
130
     * @throws Exception **/
131
	public static void main2(String[] args) throws Exception {        
132
        SAXParserFactory sf=SAXParserFactory.newInstance();
133
        sf.setNamespaceAware(true);
134
        
135
        SAXParser saxP=sf.newSAXParser();        
136
        
137
        
138
        String prb="<A:a attr=\"2222\" xmlns:A=\"http://uri-a\">" +
139
                "<!--== Prueba de -->\n" +
140
                "<b xmlns:C=\"http://uri-c\" C:a=\"2\" a=\"2\" xmlns=\"http://default\">\n" +
141
                "<b xmlns=\"http://default\">1<b>2<b/><b/><b>1</b></b></b></b>"+
142
                "</A:a>";
143
        ByteArrayInputStream is=new ByteArrayInputStream(prb.getBytes());
144
        SaxDistributor sc=new SaxDistributor("http://default","b",null,true);          
145
        //saxP.setProperty("http://xml.org/sax/properties/lexical-handler",sc);
146
        saxP.parse(is,sc);
147
        System.out.println(new String(
148
                ((ByteArrayOutputStream)((CanonWatch)sc.scs.get(1)).sc.os).toByteArray()));
149
    }
150
    public static void main(String[] args) throws Exception {        
151
                main2(null);
152
        SAXParserFactory sf=SAXParserFactory.newInstance();
153
        sf.setNamespaceAware(true);
154
        SAXParser saxP=sf.newSAXParser();
155
        long start;
156
        
157
        start=System.currentTimeMillis();
158
        int iterator=1;
159
        for (int i=0;i<iterator;i++)
160
            testExcl(saxP);
161
        
162
        System.out.println("Hecho en:"+(System.currentTimeMillis()-start));
163
        
164
        start=System.currentTimeMillis();
165
        for (int i=0;i<iterator;i++)
166
            testExcl(saxP);
167
        
168
        System.out.println("Hecho en:"+(System.currentTimeMillis()-start));
169
        
170
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
171
        dbf.setNamespaceAware(true);
172
        DocumentBuilder db=dbf.newDocumentBuilder();        
173
         start=System.currentTimeMillis();
174
        for (int i=0;i<iterator;i++)
175
            testExclDOM(db);        
176
        System.out.println("Hecho en:"+(System.currentTimeMillis()-start));
177
        
178
        start=System.currentTimeMillis();
179
        for (int i=0;i<iterator;i++)
180
            testExclDOM(db);        
181
        System.out.println("Hecho en:"+(System.currentTimeMillis()-start));
182
 
183
       
184
	}
185
    public static void testExcl(SAXParser saxP) throws Exception{
186
        
187
         SaxDistributor sc=new SaxDistributor("http://example.net","elem2",null,true);
188
         //saxP.setProperty("http://xml.org/sax/properties/lexical-handler",sc);
189
         saxP.parse(getAbsolutePath("data/org/apache/xml/security/c14n/inExcl/example2_2_1.xml"),sc);                  
190
         byte[] reference = JavaUtils.getBytesFromFile(getAbsolutePath(
191
            "data/org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml") );
192
         byte[] result = ((ByteArrayOutputStream)((CanonWatch)sc.scs.get(1)).sc.os).toByteArray();
193
         
194
         System.out.println("RESULT:"+new String(result));
195
         System.out.println("EXPECTED:"+new String(reference));
196
         boolean equals = JavaUtils.binaryCompare(reference, result);
197
         if (!equals) {
198
         	throw new RuntimeException("fail");
199
         }
200
        
201
    }
202
    static public void testExclDOM(DocumentBuilder db) throws Exception {
203
    	Document doc =
204
    		db.parse(getAbsolutePath("data/org/apache/xml/security/c14n/inExcl/example2_2_1.xml"));
205
         Node root = doc.getElementsByTagNameNS("http://example.net",
206
                                                "elem2").item(0);         
207
         Canonicalizer20010315Excl c = new Canonicalizer20010315ExclWithComments();
208
         //byte[] reference = JavaUtils.getBytesFromFile(getAbsolutePath(
209
            //"data/org/apache/xml/security/c14n/inExcl/example2_2_c14nized_exclusive.xml") );
210
         byte[] result = c.engineCanonicalizeSubTree(root);
211
         //boolean equals = JavaUtils.binaryCompare(reference, result);
212
    }
213
    
214
	/** @inheritDoc **/
215
	public void endCDATA() {
216
		
217
	}
218
    
219
	/** @inheritDoc **/
220
	public void endDTD() {
221
		
222
	}
223
    
224
	/** @inheritDoc **/
225
	public void startCDATA(){
226
		
227
	}
228
    
229
	/** @inheritDoc **/
230
	public void comment(char[] arg0, int arg1, int arg2) {
231
        if (!outputComments) {
232
        	return;
233
        }
234
		String st=new String(arg0,arg1,arg2);
235
        try {
236
        	os.write(("<!--"+st+"-->").getBytes());
237
        } catch (IOException e) {
238
            throw new RuntimeException(e);   
239
        }
240
	}
241
    final static void writeCharToUtf8(char c,OutputStream out) throws IOException{
242
        
243
        if (/*(c >= 0x0001) &&*/ (c <= 0x007F)) {
244
            out.write(c);
245
        } else if (c > 0x07FF) {
246
            out.write(0xE0 | ((c >> 12) & 0x0F));
247
            out.write(0x80 | ((c >>  6) & 0x3F));
248
            out.write(0x80 | ((c >>  0) & 0x3F));
249
            
250
        } else {
251
            out.write(0xC0 | ((c >>  6) & 0x1F));
252
            out.write(0x80 | ((c >>  0) & 0x3F));
253
            
254
        }
255
        
256
       }
257
    
258
	/** @inheritDoc **/
259
	public void endEntity(String arg0)  {
260
		
261
	}
262
    
263
	/** @inheritDoc **/
264
	public void startEntity(String arg0)  {
265
		
266
	}
267
    
268
	/** @inheritDoc **/
269
	public void startDTD(String arg0, String arg1, String arg2)  {	
270
	}
271
    private static String getAbsolutePath(String path)
272
       {
273
          String basedir = System.getProperty("basedir");
274
          if(basedir != null && !"".equals(basedir)) {
275
            path = basedir + "/" + path;
276
          }
277
          return path;
278
       }
279
    
280
    final static void writeStringToUtf8(String str,OutputStream out) throws IOException{
281
        int length=str.length();
282
        for (int i=0;i<length;i++) {
283
            char c=str.charAt(i);
284
            if (/*(c >= 0x0001) && */(c <= 0x007F)) {
285
                out.write(c);
286
            } else if (c > 0x07FF) {
287
                out.write(0xE0 | ((c >> 12) & 0x0F));
288
                out.write(0x80 | ((c >>  6) & 0x3F));
289
                out.write(0x80 | ((c >>  0) & 0x3F));
290
                
291
            } else {
292
                out.write(0xC0 | ((c >>  6) & 0x1F));
293
                out.write(0x80 | ((c >>  0) & 0x3F));
294
                
295
            }
296
        }
297
    }
298
299
	/**
300
	 * @param md
301
	 * @throws IOException
302
	 */
303
	public void setOutputStream(OutputStream md) throws IOException {
304
		md.write(((ByteArrayOutputStream)os).toByteArray());
305
        os=md;
306
	}
307
308
    
309
    public String getBase64Digest() {
310
    	try {
311
			os.flush();
312
		} catch (IOException e) {
313
			// TODO Auto-generated catch block
314
			e.printStackTrace();
315
		}
316
        if (os instanceof DigesterOutputStream)
317
        return Base64.encode(((DigesterOutputStream)os).getDigestValue());
318
        
319
        return null;
320
    }
321
    public boolean verifySignature(byte[] a) {
322
        if (os instanceof SignerOutputStream)
323
            return ((SignerOutputStream)os).verify(a); 
324
        return false;
325
    }
326
}
327
328
class AttributesCompare implements java.util.Comparator {
329
    /* (non-Javadoc)
330
	 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
331
	 */
332
	public int compare(Object obj0, Object obj1) {
333
         String[] attr0 = (String[]) obj0;
334
           String[] attr1 = (String[]) obj1;
335
          String namespaceURI0 = attr0[0];      
336
          String namespaceURI1 = attr1[0];
337
          
338
          boolean isNamespaceAttr0 =
339
             "xmlns".equals(namespaceURI0);
340
          boolean isNamespaceAttr1 =
341
             "xmlns".equals(namespaceURI1);
342
343
          if (isNamespaceAttr0) {
344
             if (isNamespaceAttr1) {
345
346
                // both are namespaces
347
                String localname0 = attr0[1];
348
                String localname1 = attr1[1];
349
350
                if (localname0.equals("xmlns")) {
351
                   localname0 = "";
352
                }
353
354
                if (localname1.equals("xmlns")) {
355
                   localname1 = "";
356
                }
357
358
                return localname0.compareTo(localname1);
359
             }
360
             // attr0 is a namespace, attr1 is not
361
             return -1;
362
             
363
          } 
364
          if (isNamespaceAttr1) {
365
366
                // attr1 is a namespace, attr0 is not
367
                return +1;
368
          } 
369
370
          // none is a namespae
371
          
372
          if (namespaceURI0 == null) {
373
            if (namespaceURI1 == null) {
374
                /*
375
                 String localName0 = attr0.getLocalName();
376
                 String localName1 = attr1.getLocalName();
377
                 return localName0.compareTo(localName1);
378
                 */
379
                
380
                String name0 = attr0[1];
381
                String name1 = attr1[1];
382
                return name0.compareTo(name1);
383
            }
384
            return -1;
385
            
386
          } 
387
          if (namespaceURI1 == null) {
388
                return +0;
389
          } 
390
          int a = namespaceURI0.compareTo(namespaceURI1);
391
                
392
          if (a != 0) {
393
            return a;
394
          }
395
          
396
          String localName0 = attr0[2];
397
          String localName1 = attr1[2];
398
          
399
          return localName0.compareTo(localName1);
400
	}
401
    
402
}
(-)src_samples/prb/SaxDistributor.java (+146 lines)
Added Link Here
1
/*
2
 * Created on Oct 24, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package prb;
8
9
import java.io.ByteArrayOutputStream;
10
import java.security.PublicKey;
11
import java.util.ArrayList;
12
import java.util.Iterator;
13
import java.util.List;
14
15
import org.xml.sax.Attributes;
16
import org.xml.sax.SAXException;
17
import org.xml.sax.helpers.DefaultHandler;
18
19
/**
20
 * @author raul
21
 *
22
 * TODO To change the template for this generated type comment go to
23
 * Window - Preferences - Java - Code Style - Code Templates
24
 */
25
public class SaxDistributor extends DefaultHandler {
26
27
    List scs=new ArrayList();
28
    
29
    SaxSign ss;
30
    PublicKey pk;
31
    boolean inSigning=false;
32
    private static final String XMLNS_URI = "http://www.w3.org/2000/09/xmldsig#";
33
  
34
	/**
35
	 * 
36
	 */
37
	public SaxDistributor(PublicKey pk,boolean excl) {
38
        this.pk=pk;
39
        scs.add(new CanonWatch(XMLNS_URI,"SignedInfo",true));
40
	}
41
    public SaxDistributor(String uri,String node,PublicKey pk,boolean excl) {
42
        this(pk,excl);
43
        scs.add(new CanonWatch(uri,node,excl));        
44
    }
45
    public void startElement(String arg0, String arg1, String arg2,
46
            Attributes arg3) throws SAXException {
47
        if (XMLNS_URI.equals(arg0) && "Signature".equals(arg1)) {
48
            inSigning=true;
49
            ss=new SaxSign(this,pk);
50
        }        
51
       Iterator it=scs.iterator() ;
52
       while (it.hasNext()) {
53
          ((CanonWatch)it.next()).updateStartState(arg0,arg1,arg2,arg3);
54
       }
55
        if (inSigning)
56
            ss.startElement(arg0,arg1,arg2,arg3);                       
57
    }
58
    
59
    /* (non-Javadoc)
60
	 * @see org.xml.sax.helpers.DefaultHandler#startPrefixMapping(java.lang.String, java.lang.String)
61
	 */
62
	public void startPrefixMapping(String arg0, String arg1)
63
			throws SAXException {
64
        Iterator it=scs.iterator() ;
65
        while (it.hasNext()) {
66
              ((CanonWatch)it.next()).sc.startPrefixMapping(arg0, arg1);
67
           }		
68
	}
69
	public void endElement(String arg0, String arg1, String arg2)
70
			throws SAXException {
71
        Iterator it=scs.iterator() ;
72
        while (it.hasNext()) {
73
              ((CanonWatch)it.next()).updateEndState(arg0,arg1,arg2);
74
           }        
75
        if (inSigning)
76
            ss.endElement(arg0,arg1,arg2);
77
        if (XMLNS_URI.equals(arg0) && "Signature".equals(arg1)) {
78
            inSigning=false;
79
        }          
80
	}
81
    /* (non-Javadoc)
82
	 * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
83
	 */
84
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
85
		if (inSigning)
86
			ss.characters(arg0, arg1, arg2);
87
        Iterator it=scs.iterator() ;
88
        while (it.hasNext()) {
89
              ((CanonWatch)it.next()).characters(arg0, arg1, arg2);
90
           }
91
	}
92
    
93
	public static void main(String[] args) {
94
	}
95
}
96
97
class CanonWatch {
98
    private Object c14nUri;
99
    private Object c14nNode;
100
    String id;
101
    private boolean already;
102
    private int anitate=0;
103
    boolean c14ning=false;
104
    SaxCanon sc=null; 
105
    public CanonWatch(String uri,String node,boolean excl) {
106
        c14nNode=node;
107
        c14nUri=uri;
108
        if (excl) {
109
          sc=new SaxExclCanon();   
110
        } else {
111
          sc=new SaxInclCanon();
112
        }
113
    }
114
    public CanonWatch() {
115
    	c14ning=true;
116
    }
117
    public void updateStartState(String arg0, String arg1, String arg2,
118
            Attributes arg3) throws SAXException {
119
        if (arg0.equals(c14nUri) && arg1.equals(c14nNode)) {
120
            if ((anitate==0) && !already) {
121
                id=arg3.getValue("id");
122
            }
123
            c14ning=!already;
124
            anitate++;
125
         }
126
        if (c14ning) 
127
            sc.startElement(arg0,arg1,arg2,arg3);  
128
    }
129
    public void updateEndState(String arg0, String arg1, String arg2) 
130
    throws SAXException {
131
        if (c14ning)
132
            sc.endElement(arg0,arg1,arg2);
133
        if ((arg0.equals(c14nUri) && arg1.equals(c14nNode))) {
134
            anitate--;
135
            if (anitate==0) {                               
136
                c14ning=false;
137
                already=true;
138
            }
139
         }
140
    }
141
    public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
142
        if (c14ning) {            
143
            sc.characters(arg0, arg1, arg2);
144
        }
145
    }
146
}
(-)src_samples/prb/SaxExclCanon.java (+66 lines)
Added Link Here
1
/*
2
 * Created on Nov 11, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package prb;
8
9
import java.util.Iterator;
10
import java.util.SortedSet;
11
import java.util.TreeSet;
12
13
import org.xml.sax.Attributes;
14
15
/**
16
 * @author raul
17
 *
18
 * TODO To change the template for this generated type comment go to
19
 * Window - Preferences - Java - Code Style - Code Templates
20
 */
21
public class SaxExclCanon extends SaxCanon {
22
23
	public static void main(String[] args) {
24
	}
25
26
	/**
27
	 * @param arg2
28
	 * @param arg3
29
	 * @return
30
	 */
31
	SortedSet handleAttributes(String arg2, Attributes arg3) {
32
		SortedSet visiblyUtilized =new TreeSet();        
33
	    SortedSet s=new TreeSet(new AttributesCompare());
34
	    for (int i=0;i<arg3.getLength();i++) {
35
	        String qname=arg3.getQName(i);
36
	        int colon=qname.indexOf(':');            
37
	        String prefix=qname;
38
	        if (colon>0) {
39
	        	prefix=qname.substring(0,colon);                
40
	        } 
41
	        if (!"xml".equals(prefix)) {
42
	        	visiblyUtilized.add(prefix);
43
	        }            
44
	        String []attr= {arg3.getURI(i),arg3.getValue(i),qname};
45
	        s.add(attr);                        
46
	    }
47
	    int colon=arg2.indexOf(':');
48
	    String prefix=null;
49
	    if (colon>0) {            
50
	       prefix=arg2.substring(0,arg2.indexOf(':'));                     
51
	       visiblyUtilized.add(prefix);
52
	    } else {
53
	    	visiblyUtilized.add("xmlns");
54
	    }
55
	    Iterator it=visiblyUtilized.iterator();
56
	    while (it.hasNext()) {
57
	        String prefix1=(String)it.next();                                 
58
	        String[] key=(String [])ns.getMapping(prefix1);
59
	        if (key==null) {
60
	            continue;
61
	        }
62
	        s.add(key);
63
	    }
64
		return s;
65
	}
66
}
(-)src_samples/prb/SaxInclCanon.java (+36 lines)
Added Link Here
1
/*
2
 * Created on Nov 11, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package prb;
8
9
import java.util.SortedSet;
10
import java.util.TreeSet;
11
12
import org.xml.sax.Attributes;
13
14
/**
15
 * @author raul
16
 *
17
 * TODO To change the template for this generated type comment go to
18
 * Window - Preferences - Java - Code Style - Code Templates
19
 */
20
public class SaxInclCanon extends SaxCanon {
21
22
	/* (non-Javadoc)
23
	 * @see prb.SaxCanon#handleAttributes(java.lang.String, org.xml.sax.Attributes)
24
	 */
25
	SortedSet handleAttributes(String arg2, Attributes arg3) {
26
        SortedSet s=new TreeSet(new AttributesCompare());
27
        for (int i=0;i<arg3.getLength();i++) {
28
            String qname=arg3.getQName(i);          
29
            String []attr= {arg3.getURI(i),arg3.getValue(i),qname};
30
            s.add(attr);                        
31
        }
32
        ns.getUnrenderedNodes(s);
33
        return s;
34
	}
35
36
}
(-)src_samples/prb/SaxPrb.java (+312 lines)
Added Link Here
1
/*
2
 * Created on Oct 24, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package prb;
8
9
import java.io.ByteArrayInputStream;
10
import java.io.ByteArrayOutputStream;
11
import java.io.File;
12
import java.io.FileInputStream;
13
import java.io.FileOutputStream;
14
import java.io.IOException;
15
import java.io.InputStream;
16
import java.security.KeyPair;
17
import java.security.KeyPairGenerator;
18
import java.security.KeyStore;
19
import java.security.NoSuchAlgorithmException;
20
import java.security.PrivateKey;
21
import java.security.PublicKey;
22
import java.security.cert.CertificateFactory;
23
import java.security.cert.X509Certificate;
24
import java.util.AbstractCollection;
25
import java.util.logging.Level;
26
import java.util.logging.Logger;
27
import java.util.zip.GZIPInputStream;
28
29
import javax.xml.parsers.DocumentBuilder;
30
import javax.xml.parsers.FactoryConfigurationError;
31
import javax.xml.parsers.ParserConfigurationException;
32
import javax.xml.parsers.SAXParser;
33
import javax.xml.parsers.SAXParserFactory;
34
35
import org.apache.commons.logging.LogFactory;
36
import org.apache.xml.security.Init;
37
import org.apache.xml.security.c14n.CanonicalizationException;
38
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
39
import org.apache.xml.security.exceptions.XMLSecurityException;
40
import org.apache.xml.security.signature.ObjectContainer;
41
import org.apache.xml.security.signature.XMLSignature;
42
import org.apache.xml.security.signature.XMLSignatureException;
43
import org.apache.xml.security.transforms.TransformationException;
44
import org.apache.xml.security.transforms.Transforms;
45
import org.apache.xml.security.utils.Base64;
46
import org.apache.xml.security.utils.Constants;
47
import org.apache.xml.security.utils.IdResolver;
48
import org.apache.xml.security.utils.SignerOutputStream;
49
import org.apache.xml.security.utils.XMLUtils;
50
import org.w3c.dom.Document;
51
import org.w3c.dom.Element;
52
53
/**
54
 * @author raul
55
 *
56
 * TODO To change the template for this generated type comment go to
57
 * Window - Preferences - Java - Code Style - Code Templates
58
 */
59
public class SaxPrb {
60
61
	private static ByteArrayOutputStream f;
62
	/**
63
	 * 
64
	 */
65
	public SaxPrb() {
66
		super();
67
		// TODO Auto-generated constructor stub
68
	}
69
    public static void main(String[] args)  throws Exception {
70
        Init.init();
71
        javax.xml.parsers.DocumentBuilderFactory dbf =
72
            javax.xml.parsers.DocumentBuilderFactory.newInstance();
73
74
         dbf.setNamespaceAware(true);
75
76
         javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
77
     testBug(db);   
78
    }
79
	public static void main2(String[] args)  throws Exception {
80
        Init.init();
81
        Logger.getLogger("org.apache.xml.security.signature.Reference").setLevel(Level.OFF);
82
        check122MFile();
83
        javax.xml.parsers.DocumentBuilderFactory dbf =
84
             javax.xml.parsers.DocumentBuilderFactory.newInstance();
85
86
          dbf.setNamespaceAware(true);
87
88
          javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
89
        KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
90
        KeyPair kp=kpg.generateKeyPair();        
91
         createAndTestSignature(kp,db);
92
         
93
         SAXParserFactory sf=SAXParserFactory.newInstance();
94
         sf.setNamespaceAware(true);
95
         SAXParser saxP=sf.newSAXParser();
96
         int iterations=100;
97
         long start=System.currentTimeMillis();         
98
         for (int i=0;i<iterations;i++) {
99
              checkSox(saxP,f.toByteArray(),kp.getPublic());
100
         }
101
         System.out.println("Tardo SAX:"+(System.currentTimeMillis()-start));
102
         start=System.currentTimeMillis();
103
         for (int i=0;i<iterations;i++) {
104
              checkSox(saxP,f.toByteArray(),kp.getPublic());
105
         }
106
         System.out.println("Tardo SAX:"+(System.currentTimeMillis()-start));
107
        
108
         start=System.currentTimeMillis();
109
         for (int i=0;i<iterations;i++) {
110
              checkDOM(f.toByteArray(),kp.getPublic(),db);
111
         }
112
         System.out.println("Tardo DOM:"+(System.currentTimeMillis()-start));
113
         start=System.currentTimeMillis();
114
         for (int i=0;i<iterations;i++) {
115
              checkDOM(f.toByteArray(),kp.getPublic(),db);
116
         }
117
         System.out.println("Tardo DOM:"+(System.currentTimeMillis()-start));
118
              //check122MFile();
119
           }
120
    /**
121
	 * @throws NoSuchAlgorithmException
122
	 * @throws FactoryConfigurationError
123
	 * @throws ParserConfigurationException
124
	 * @throws XMLSecurityException
125
	 * @throws TransformationException
126
	 * @throws XMLSignatureException
127
	 * @throws IOException
128
	 * @throws CanonicalizationException
129
	 * @throws InvalidCanonicalizerException
130
	 */
131
	private static void createAndTestSignature(KeyPair kp,DocumentBuilder db) throws NoSuchAlgorithmException, FactoryConfigurationError, ParserConfigurationException, XMLSecurityException, TransformationException, XMLSignatureException, IOException, CanonicalizationException, InvalidCanonicalizerException {
132
		//J-
133
		    
134
		  //J+
135
		
136
		 
137
		  org.w3c.dom.Document doc = db.newDocument();
138
		  String BaseURI = "#1";
139
		  XMLSignature sig = new XMLSignature(doc, BaseURI,
140
		                                      XMLSignature.ALGO_ID_SIGNATURE_RSA,
141
		                                      Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
142
		  Element anElement = doc.createElementNS(null, "RootObject");              
143
		  Element anElement2 = doc.createElementNS(null, "UnderObject");
144
		  anElement2.setAttribute("id","1");
145
		  anElement.appendChild(anElement2);
146
		  anElement.appendChild(sig.getElement());
147
		  doc.appendChild(anElement);
148
		  anElement2.appendChild(doc.createTextNode("A text in a box"));
149
          Element anElement3 =doc.createElementNS(null,"OtherObject");
150
          anElement2.appendChild(anElement3);
151
          anElement3.appendChild(doc.createElementNS(null,"OtherObject2"));
152
          anElement3.appendChild(doc.createElementNS(null,"OtherObject6"));
153
          anElement3.appendChild(doc.createElementNS(null,"OtherObject"));
154
		  {
155
		     Transforms transforms = new Transforms(doc);
156
157
		     transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
158
		     sig.addDocument("#1" , transforms, Constants.ALGO_ID_DIGEST_SHA1);
159
		  }
160
161
		  {
162
		     System.out.println("Start signing");
163
		     sig.sign(kp.getPrivate());
164
		     System.out.println("Finished signing");
165
              System.out.println("verifying in memory:"+sig.checkSignatureValue(kp.getPublic()));
166
		  }
167
168
		  f = new ByteArrayOutputStream();
169
		XMLUtils.outputDOMc14nWithComments(doc, f);
170
		  f.close();
171
		  System.out.println("Wrote signature to:" + new String(f.toByteArray()));
172
173
		  for (int i=0; i<sig.getSignedInfo().getSignedContentLength(); i++) {
174
		     System.out.println("--- Signed Content follows ---");
175
		     System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
176
		  }
177
		  ByteArrayOutputStream os=new ByteArrayOutputStream();
178
		  sig.getSignedInfo().signInOctectStream(os);
179
		  System.out.println(new String(os.toByteArray()));
180
	}
181
182
	public static void check122MFile() throws Exception{
183
        
184
    	String certS="-----BEGIN CERTIFICATE-----\n"+
185
        "MIIDCDCCAfCgAwIBAgIEPhq2jTANBgkqhkiG9w0BAQUFADBAMQswCQYDVQQGEwJISzESMBAGA1UE\n" + 
186
                "ChMJQmFsdGltb3JlMQwwCgYDVQQLEwNHU1MxDzANBgNVBAMTBlRlc3RDQTAeFw0wMzAxMDcxMTE0\n" + 
187
                "MjFaFw0wNDAxMDcxMTE0MjFaMEMxCzAJBgNVBAYTAkhLMRIwEAYDVQQKEwlCYWx0aW1vcmUxDDAK\n" + 
188
                "BgNVBAsTA0dTUzESMBAGA1UEAxMJQmFsdHVzZXIxMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\n" + 
189
                "gQCsCDe8BAn/w7PJOYVV/WXudE64m2MNDZNNjPsxUJXcTDYmcomd4n3niekOdsxTG1PPesMgUxhw\n" + 
190
                "deh2OgpTXsZNOW77pRFUQMzNzU/Fc+YVUDN7I4hFWuxd3PMP8gWI1dJnljyJ86QXjxESGVglpXrK\n" + 
191
                "3TzvIbBnZzUCrOGYY6tY2wIDAQABo4GKMIGHMA4GA1UdDwEB/wQEAwIDyDB1BgNVHR8EbjBsMGqg\n" + 
192
                "aKBmhmRsZGFwOi8vcGMyMDMuYmFsdGltb3JlLmNvbS5oazozODkvY249VGVzdENBLG91PUdTUyxv\n" + 
193
                "PUJhbHRpbW9yZSxjPUhLP2NlcnRpZmljYXRlcmV2b2NhdGlvbmxpc3Q7YmluYXJ5MA0GCSqGSIb3\n" + 
194
                "DQEBBQUAA4IBAQCdqNoHr/bJlTrVkuVYS58wNswmSWA6HLaiggLj6i7N/qav9GNpyNLc157JeoFW\n" + 
195
                "4J/tT7NLrKWzZW4sRWRnAF5O0xbZz7eBS+8kBttjejHgZKx2n+QCjVfOwghsUxCBfTgAqN9anUvP\n" + 
196
                "IuZYggYfZqLTY+MY6wdnXb1mqb8at6aztbuKnvGnJJITb8Bi4fsaD060dd4Eqj7HZZZluXhGm+z8\n" + 
197
                "KL3e8qjNdZabdyBCSrdDRpWXckTD5lU3bivlgVN8Ree9jRM1jEjpCOwhgN3Xvde4BkscL2ZGPZCC\n" + 
198
                "LH9mea9wzIkfbjm7wdqEwGghT0GucFPl5t9P/gltNfYkPSq+IjcP\n"+
199
                "-----END CERTIFICATE-----\n";
200
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
201
        X509Certificate cert=(X509Certificate)cf.generateCertificate(new ByteArrayInputStream(certS.getBytes()));
202
        SAXParserFactory sf=SAXParserFactory.newInstance();
203
        sf.setNamespaceAware(true);
204
        SAXParser saxP=sf.newSAXParser();
205
        
206
        InputStream is=new GZIPInputStream(new FileInputStream("122M_sig.xml.gz"));
207
        long start=System.currentTimeMillis();
208
        SaxDistributor sd=new SaxDistributor("http://www.w3.org/2000/09/xmldsig#","Object",cert.getPublicKey(),false);
209
        //sd.scs.add(new CanonWatch());
210
        saxP.parse(is,sd);
211
        System.out.println("duracion:"+(System.currentTimeMillis()-start));
212
        
213
        //System.out.println("RESULT:"+new String(result));
214
        System.out.println("RESULT:"+sd.ss.validateReferences());
215
        System.out.println("RESULT sd:"+sd.ss.validateSignature());
216
        
217
    }
218
    public static void checkSox(SAXParser saxP,byte sig[],PublicKey pk) throws Exception {        
219
        
220
    	ByteArrayInputStream is=new ByteArrayInputStream(sig);
221
        SaxDistributor sd=new SaxDistributor("","UnderObject",pk,true);
222
        //sd.scs.add(new CanonWatch());
223
        saxP.parse(is,sd);
224
        //byte[] result = ((CanonWatch)sd.scs.get(1)).sc.os.toByteArray();
225
        
226
        //System.out.println("RESULT:"+new String(result));
227
        if (!(sd.ss.validateReferences() && sd.ss.validateSignature())) {
228
        	throw new RuntimeException("ERROR SAX");
229
        }
230
        //System.out.println("RESULT:"+sd.ss.validateReferences());
231
        //.System.out.println("RESULT sd:"+sd.ss.validateSignature());
232
        //result = ((CanonWatch)sd.scs.get(0)).sc.os.toByteArray();
233
        
234
        //System.out.println("RESULT:"+new String(result));
235
    }
236
    
237
    public static void checkDOM(byte sig[],PublicKey pk, DocumentBuilder db) throws Exception {
238
        Document doc=db.parse(new ByteArrayInputStream(sig));
239
        //System.out.println();
240
        IdResolver.registerElementById((Element)doc.getFirstChild().getFirstChild(),"1");
241
        XMLSignature xs=new XMLSignature((Element)doc.getFirstChild().getFirstChild().getNextSibling(),"");
242
       if (!xs.checkSignatureValue(pk))
243
            throw new RuntimeException("FAIL DOM");
244
         
245
    }
246
    public static void testBug(DocumentBuilder db) throws Exception{
247
     String signagture="<Assertion AssertionID=\"932aa4da-9aeb-484e-8ecf-99b4609c48f6\" IssueInstant=\"2004-11-18T05:26:26Z\" Issuer=\"DC=org,DC=DOEGrids,OU=Certificate Authorities,CN=DOEGrids CA 1\" MajorVersion=\"1\" MinorVersion=\"0\" xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\"><Conditions NotBefore=\"2004-11-18T05:26:26Z\" NotOnOrAfter=\"2004-11-18T05:28:06Z\"/><AuthorizationDecisionStatement Decision=\"Permit\" Resource=\"FTPNamespace|ftp://sample1.org\" xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\"><Subject xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\"><NameIdentifier Format=\"#X509SubjectName\" NameQualifier=\"dummyDN\">dummy DN</NameIdentifier><SubjectConfirmation><ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:am:X509-PKI</ConfirmationMethod></SubjectConfirmation></Subject><Action Namespace=\"fileType\" xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\">read</Action><Action Namespace=\"directory\" xmlns=\"urn:oasis:names:tc:SAML:1.0:assertion\">read</Action></AuthorizationDecisionStatement><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
248
            "<ds:SignedInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
249
            "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
250
            "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
251
            "<ds:Reference URI=\"\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
252
            "<ds:Transforms xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:signs=\"urn:oasis:names:tc:SAML:1.0:assertion\">\n" + 
253
            "<ds:Transform Algorithm=\"http://www.w3.org/2002/06/xmldsig-filter2\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
254
            "<dsig-xpath:XPath Filter=\"intersect\" xmlns:dsig-xpath=\"http://www.w3.org/2002/06/xmldsig-filter2\">here()/ancestor::signs:Assertion[1]</dsig-xpath:XPath>\n" + 
255
            "<dsig-xpath:XPath Filter=\"subtract\" xmlns:dsig-xpath=\"http://www.w3.org/2002/06/xmldsig-filter2\">here()/ancestor::ds:Signature[1]</dsig-xpath:XPath>\n" + 
256
            "</ds:Transform>\n" + 
257
            "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"><ec:InclusiveNamespaces PrefixList=\"code ds kind rw saml samlp signs #default xsd xsi\" xmlns:ec=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/></ds:Transform>\n" + 
258
            "</ds:Transforms>\n" + 
259
            "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
260
            "<ds:DigestValue xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">1P4tHsFzvYgx4KAEBHpQMSSy1pM=</ds:DigestValue>\n" + 
261
            "</ds:Reference>\n" + 
262
            "</ds:SignedInfo>\n" + 
263
            "<ds:SignatureValue xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
264
            "S78gPVnzpVjNineV6V6I0Kn8zh8dcxz2vKnj3RmORx86nQfWnFRdP1RCwRkDOpiuvKXAQsSFpQRa\n" + 
265
            "GkerMG/7iQ==\n" + 
266
            "</ds:SignatureValue>\n" + 
267
            "<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
268
            "<ds:X509Data xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
269
            "<ds:X509Certificate xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
270
            "MIICuTCCAaGgAwIBAgIEEJvQxTANBgkqhkiG9w0BAQQFADBeMRMwEQYKCZImiZPyLGQBGRYDb3Jn\n" + 
271
            "MRgwFgYKCZImiZPyLGQBGRYIZG9lZ3JpZHMxDzANBgNVBAsTBlBlb3BsZTEcMBoGA1UEAxMTU2Ft\n" + 
272
            "dWVsIE1lZGVyIDE5NjM0NDAeFw0wNDExMTgwNDMwMzBaFw0wNDExMTgxNjM1MzBaMHIxEzARBgoJ\n" + 
273
            "kiaJk/IsZAEZFgNvcmcxGDAWBgoJkiaJk/IsZAEZFghkb2VncmlkczEPMA0GA1UECxMGUGVvcGxl\n" + 
274
            "MRwwGgYDVQQDExNTYW11ZWwgTWVkZXIgMTk2MzQ0MRIwEAYDVQQDEwkyNzg2NDY5ODEwXDANBgkq\n" + 
275
            "hkiG9w0BAQEFAANLADBIAkEAyEix18UyUMK2w3Onb/7EXCSrfnAMxwotpvVF6KJ/qA5xcAWVizaJ\n" + 
276
            "UPdtmGZY6It2l+DSDK/nvoLRlX/LH3xnRwIDAQABozMwMTAOBgNVHQ8BAf8EBAMCBLAwHwYKKwYB\n" + 
277
            "BAGbUAGBXgEB/wQOMAwwCgYIKwYBBQUHFQEwDQYJKoZIhvcNAQEEBQADggEBAEVIF9ZDPZxZL0wh\n" + 
278
            "1tHZi0VdJrjug8g59cTip5dWcKz7eusKWkR0eXt/vQ6gv0KqYLO2NUt8zVk1d32Z6v3nrg2NzxNR\n" + 
279
            "EjwGqrxB7sZGkNnwWNKW+Ao8AkfE5gfqzVmuEOGDbKlXMeL2XYZhO5jpUSAMCQawl0SvCtDbfxmH\n" + 
280
            "ygUuKUeTCLA4tSAXKcxTSkvNAV0W/KObKSOoZ9qq3zG4f2+GqujrPa1ahRo3uwl7YIJTEjkmaPqC\n" + 
281
            "MFvJdC4D3LLb8WyB8LYofRVpwc0TtkotbiwjIEy4CN59sLtrTx5TGbDWDiK0Ukw6ichNP3Nr44i0\n" + 
282
            "eC8h/LpG0SJgzgHt0LY2agc=\n" + 
283
            "</ds:X509Certificate>\n" + 
284
            "<ds:X509Certificate xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
285
            "MIIDpzCCAo+gAwIBAgICBVEwDQYJKoZIhvcNAQEFBQAwaTETMBEGCgmSJomT8ixkARkWA29yZzEY\n" + 
286
            "MBYGCgmSJomT8ixkARkWCERPRUdyaWRzMSAwHgYDVQQLExdDZXJ0aWZpY2F0ZSBBdXRob3JpdGll\n" + 
287
            "czEWMBQGA1UEAxMNRE9FR3JpZHMgQ0EgMTAeFw0wNDAxMDcxNzEyNTJaFw0wNTAxMDYxNzEyNTJa\n" + 
288
            "MF4xEzARBgoJkiaJk/IsZAEZFgNvcmcxGDAWBgoJkiaJk/IsZAEZFghkb2VncmlkczEPMA0GA1UE\n" + 
289
            "CxMGUGVvcGxlMRwwGgYDVQQDExNTYW11ZWwgTWVkZXIgMTk2MzQ0MIIBIjANBgkqhkiG9w0BAQEF\n" + 
290
            "AAOCAQ8AMIIBCgKCAQEAmsC01HNrzO0ddRWo6IajmK8A0iRCebL206gFwzH9uJHhH6pcYu1ro6Es\n" + 
291
            "8Db36wb0u04DFhUsQBjEUoLanK9S7QhxeD9jkkpycX8mwfJhzxCeFMLG743Es0EfQJZNF4cOtnKy\n" + 
292
            "zB8hBYbc52q5Xbo7Xdjz81yuzTYdyXnkxUgDCdXoPeYiPy+eRCJFnqo6lQ9QKhMTVWsfEUPpfoSy\n" + 
293
            "C/YkMN0ag3H2bmWouZ/YauOQfCzCTtFDKP3+RroBhYDOkEoqyq77z204crdGYdQUlE5ata5ZbFtL\n" + 
294
            "uBuCXkup1Y0f+AcPFiN8M24E3L7AJQ9VAJSELvfz8IWSBsFd+meEl/NanwIDAQABo2QwYjARBglg\n" + 
295
            "hkgBhvhCAQEEBAMCBeAwDgYDVR0PAQH/BAQDAgTwMBwGA1UdEQQVMBOBEW1lZGVyQG1jcy5hbmwu\n" + 
296
            "Z292MB8GA1UdIwQYMBaAFMoZHRKObqQ4XULUMQ4I29mNFw1dMA0GCSqGSIb3DQEBBQUAA4IBAQAq\n" + 
297
            "30xAqkVK4dmXOVLbGqmcEaNDBaJeURYotUiAxrt9r/fTlLWpOUf3Dh2kQZiS3vJPc2GDvM7AF/AO\n" + 
298
            "dfsrJ1wSmh44qubqsorBVy23urTI1nOvSMwaMJ5k03GiVdu0MGiMFDlz4W1OYgLVThxtFH7dQsuS\n" + 
299
            "EiGvKK1LWZLT32b+uSI75K+x/UryJHFEpbSLCer6Tb31ZItg+eeUs08276Nu4tUyN6CIPGizueOd\n" + 
300
            "ebGhj6o9YuS9rsbxUC73TabuZX6EeohIFN73+2nOX0kn0JgN+qAbh3ARdFj8f6zFRuzbeYX1Okxh\n" + 
301
            "WUPNYSMbA+vV+rp6lv0+FN7E9Ao+1q9dLdLX\n" + 
302
            "</ds:X509Certificate>\n" + 
303
            "</ds:X509Data>\n" + 
304
            "</ds:KeyInfo></ds:Signature></Assertion>\n";
305
     Document doc=db.parse(new ByteArrayInputStream(signagture.getBytes()));
306
     Element el=(Element)doc.getFirstChild().getFirstChild().getNextSibling().getNextSibling();
307
     System.out.println(el);
308
     XMLSignature sig=new XMLSignature(el,"");
309
     System.out.println(new String(sig.getSignedInfo().getReferencedContentAfterTransformsItem(0).getBytes()));
310
    }
311
	}
312
(-)src_samples/prb/SaxSign.java (+219 lines)
Added Link Here
1
/*
2
 * Created on Oct 23, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package prb;
8
9
10
import java.io.BufferedOutputStream;
11
import java.io.IOException;
12
import java.nio.BufferOverflowException;
13
import java.security.MessageDigest;
14
import java.security.PublicKey;
15
16
import javax.xml.parsers.SAXParser;
17
import javax.xml.parsers.SAXParserFactory;
18
19
import org.apache.xml.security.algorithms.JCEMapper;
20
import org.apache.xml.security.algorithms.MessageDigestAlgorithm;
21
import org.apache.xml.security.algorithms.SignatureAlgorithm;
22
import org.apache.xml.security.exceptions.Base64DecodingException;
23
import org.apache.xml.security.exceptions.XMLSecurityException;
24
import org.apache.xml.security.signature.XMLSignatureException;
25
import org.apache.xml.security.utils.Base64;
26
import org.apache.xml.security.utils.DigesterOutputStream;
27
import org.apache.xml.security.utils.SignerOutputStream;
28
import org.w3c.dom.Document;
29
import org.w3c.dom.Element;
30
import org.xml.sax.Attributes;
31
import org.xml.sax.SAXException;
32
import org.xml.sax.helpers.DefaultHandler;
33
34
/**
35
 * @author raul
36
 *
37
 */
38
public class SaxSign extends DefaultHandler {
39
40
	private static final String XMLNS_URI = "http://www.w3.org/2000/09/xmldsig#";
41
	private boolean inSignature;
42
	boolean inReference=false;
43
    boolean inSignatureValue=false;    
44
    ReferenceHolder ref;
45
    SaxDistributor sd;
46
    SignerOutputStream si=null;
47
    String signatureValue=null;
48
    PublicKey pk;
49
	private SignatureAlgorithm sa;
50
	/**
51
	 * 
52
	 */
53
	public SaxSign(SaxDistributor sd,PublicKey pk) {
54
        this.pk=pk;
55
		this.sd=sd;
56
	}
57
    
58
    /* (non-Javadoc)
59
	 * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
60
	 */
61
	public void startElement(String arg0, String arg1, String arg2,
62
			Attributes arg3) throws SAXException {
63
        if (XMLNS_URI.equals(arg0) && "Signature".equals(arg1)) {
64
            inSignature=true;
65
        }        
66
        if (!inSignature)
67
            return; //Check if reference
68
        
69
        if (XMLNS_URI.equals(arg0) && "Reference".equals(arg1)) {
70
            inReference=true;
71
            ref=new ReferenceHolder(arg3,((CanonWatch)sd.scs.get(1)).sc);
72
        }
73
        if (XMLNS_URI.equals(arg0) && "SignatureValue".equals(arg1)) {
74
            inSignatureValue=true;
75
        }
76
        if (XMLNS_URI.equals(arg0) && "SignatureMethod".equals(arg1)) {
77
            updateSignatureStream(arg3);
78
        }
79
80
        if (inReference) {
81
        	ref.update(arg0,arg1,arg3);
82
        }
83
	}
84
    
85
	/**
86
	 * @param arg3
87
	 */
88
	private void updateSignatureStream(Attributes arg3) {
89
		try {
90
		    sa = new SignatureAlgorithm(arg3.getValue("Algorithm"));
91
			si=
92
		        new SignerOutputStream(
93
		                sa);
94
             if (pk!=null) {
95
                sa.initVerify(pk);
96
             	try {
97
					((CanonWatch)sd.scs.get(0)).sc.setOutputStream(new BufferedOutputStream(si));
98
				} catch (IOException e1) {
99
					// TODO Auto-generated catch block
100
					e1.printStackTrace();
101
				}
102
             }
103
		    
104
		} catch (XMLSecurityException e) {
105
			throw new RuntimeException("No algoth",e);
106
		}
107
	}
108
109
	public void endElement(String arg0, String arg1, String arg2)
110
			throws SAXException {
111
        if (XMLNS_URI.equals(arg0) && "Signature".equals(arg1)) {
112
            inSignature=false;
113
        }
114
        if (XMLNS_URI.equals(arg0) && "Reference".equals(arg1)) {
115
            inReference=false;            
116
        }
117
        if (XMLNS_URI.equals(arg0) && "SignatureValue".equals(arg1)) {
118
            inSignatureValue=false;
119
        }
120
        if (inReference) {
121
            ref.update(arg0,arg1);
122
        }        
123
	}
124
    public boolean validateReferences() {       
125
    	return ref.validate();
126
    }
127
    
128
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
129
		if (inReference) {
130
			ref.setValue(new String(arg0,arg1,arg2));
131
        }
132
        if (inSignatureValue) {
133
            if (signatureValue!=null)
134
            	signatureValue+=new String(arg0,arg1,arg2);
135
            else
136
                signatureValue=new String(arg0,arg1,arg2);
137
        }
138
	}
139
    
140
    public boolean validateSignature() {
141
        //System.out.println("a="+signatureValue);
142
        try {
143
			((CanonWatch)sd.scs.get(0)).sc.os.flush();
144
            return sa.verify(Base64.decode(signatureValue));
145
		} catch (Exception e) {
146
			throw new RuntimeException(e);
147
		}    	
148
    }
149
}
150
151
class ReferenceHolder {
152
   String uri;
153
   boolean inDigest=false;
154
   String digestValue;
155
   SaxCanon sc;
156
   DigesterOutputStream di;
157
   
158
   public ReferenceHolder(Attributes atrs,SaxCanon sc) {
159
   	  uri=atrs.getValue("URI");
160
      this.sc=sc;
161
   }
162
   public void update(String uri,String localname,Attributes arg3) {
163
   	     if ("Transform".equals(localname)) {
164
   	     	if (!"http://www.w3.org/2001/10/xml-exc-c14n#".
165
                    equals(arg3.getValue("Algorithm"))) {
166
   	     		throw new RuntimeException("Only xml-exc-c14n transformation accepted,sorry");                
167
            }
168
         }
169
         if ("DigestMethod".equals(localname)) {
170
         	String algorithmURI=arg3.getValue("Algorithm");
171
             String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);              
172
173
             MessageDigest md;
174
175
             try {
176
                md = MessageDigest.getInstance(algorithmID);
177
             } catch (java.security.NoSuchAlgorithmException ex) {
178
                Object[] exArgs = { algorithmID,
179
                                    ex.getLocalizedMessage() };
180
181
                throw new RuntimeException("No such algorithm");
182
             }
183
             this.di=new DigesterOutputStream(md);
184
             try {
185
				sc.setOutputStream(new BufferedOutputStream(di));
186
			} catch (IOException e) {
187
				// TODO Auto-generated catch block
188
				e.printStackTrace();
189
			}
190
             
191
         }
192
         if ("DigestValue".equals(localname)) {
193
            inDigest=true;
194
         }
195
   }
196
   public boolean validate() {
197
   	try {
198
		sc.os.flush();
199
	} catch (IOException e) {
200
201
	}
202
   	    boolean b=digestValue.equals(Base64.encode(di.getDigestValue()));
203
        if (!b) {
204
        	System.out.println("fail the value:"+sc.getBase64Digest());
205
        }
206
        return b;
207
   }
208
   public void setValue(String value) {
209
   	  if (inDigest) {
210
        //System.out.println("Setting digest:"+value);
211
        digestValue=value;
212
      }
213
   }
214
   public void update(String uri,String localname) {
215
   	    if ("DigestValue".equals(localname)) {
216
   	    	inDigest=false;
217
   	    }
218
   }
219
}
(-)src_unitTests/org/apache/xml/security/test/encryption/AllTests.java (+35 lines)
Added Link Here
1
/*
2
 * Created on Oct 5, 2004
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package org.apache.xml.security.test.encryption;
8
9
import java.security.Provider;
10
import java.security.Security;
11
12
import org.bouncycastle.jce.provider.BouncyCastleProvider;
13
14
import junit.framework.Test;
15
import junit.framework.TestSuite;
16
17
/**
18
 * @author raul
19
 *
20
 * TODO To change the template for this generated type comment go to
21
 * Window - Preferences - Java - Code Style - Code Templates
22
 */
23
public class AllTests {
24
25
	public static Test suite()  throws Exception {
26
        Security.addProvider(new BouncyCastleProvider());
27
		TestSuite suite = new TestSuite(
28
				"Test for org.apache.xml.security.test.encryption");
29
		//$JUnit-BEGIN$
30
		suite.addTestSuite(XMLCipherTester.class);
31
		suite.addTest(BaltimoreEncTest.suite());        
32
		//$JUnit-END$
33
		return suite;
34
	}
35
}

Return to bug 32657