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

(-).cvsignore (+2 lines)
Lines 2-4 Link Here
2
.project
2
.project
3
*.properties
3
*.properties
4
build
4
build
5
10M_d_e.xml
6
122M_sig.xml.gz
(-)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 (-8 / +8 lines)
Lines 81-88 Link Here
81
            
81
            
82
      for (int i = 0; i < attrsLength; i++) {
82
      for (int i = 0; i < attrsLength; i++) {
83
         Attr N = (Attr) attrs.item(i);
83
         Attr N = (Attr) attrs.item(i);
84
         String NName=N.getLocalName();
85
         String NValue=N.getValue();
86
         String NUri =N.getNamespaceURI();
84
         String NUri =N.getNamespaceURI();
87
85
88
         if (!XMLNS_URI.equals(NUri)) {
86
         if (!XMLNS_URI.equals(NUri)) {
Lines 90-95 Link Here
90
            result.add(N);
88
            result.add(N);
91
            continue;
89
            continue;
92
         }
90
         }
91
         String NName=N.getLocalName();
92
         String NValue=N.getValue();
93
         
93
         
94
         if (XML.equals(NName)
94
         if (XML.equals(NName)
95
                 && XML_LANG_URI.equals(NValue)) {
95
                 && XML_LANG_URI.equals(NValue)) {
Lines 97-108 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
104
             result.add(n);
104
             result.add(n);
105
             if (C14nHelper.namespaceIsRelative(N)) {
105
             if (!C14nHelper.namespaceIsAbsolute(NValue)) {
106
                Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
106
                Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
107
                throw new CanonicalizationException(
107
                throw new CanonicalizationException(
108
                   "c14n.Canonicalizer.RelativeNamespace", exArgs);
108
                   "c14n.Canonicalizer.RelativeNamespace", exArgs);
Lines 227-236 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.namespaceIsAbsolute(NValue)) {
234
                       Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
234
                       Object exArgs[] = { E.getTagName(), NName, N.getNodeValue() };
235
                       throw new CanonicalizationException(
235
                       throw new CanonicalizationException(
236
                          "c14n.Canonicalizer.RelativeNamespace", exArgs);
236
                          "c14n.Canonicalizer.RelativeNamespace", exArgs);
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 (-14 / +13 lines)
Lines 107-118 Link Here
107
	 * @param E
107
	 * @param E
108
	 * @throws CanonicalizationException
108
	 * @throws CanonicalizationException
109
	 */
109
	 */
110
	Iterator handleAttributesSubtree(Element E,NameSpaceSymbTable ns)
110
	Iterator handleAttributesSubtree(final Element E,final NameSpaceSymbTable ns)
111
			throws CanonicalizationException {
111
			throws CanonicalizationException {
112
		// System.out.println("During the traversal, I encountered " +
112
		// System.out.println("During the traversal, I encountered " +
113
		// XMLUtils.getXPath(E));
113
		// XMLUtils.getXPath(E));
114
		// result will contain the attrs which have to be outputted
114
		// result will contain the attrs which have to be outputted
115
		SortedSet result = new TreeSet(COMPARE);
115
		final SortedSet result = new TreeSet(COMPARE);
116
		NamedNodeMap attrs=null;
116
		NamedNodeMap attrs=null;
117
        
117
        
118
		int attrsLength = 0;
118
		int attrsLength = 0;
Lines 124-131 Link Here
124
		SortedSet visiblyUtilized =(SortedSet) _inclusiveNSSet.clone();
124
		SortedSet visiblyUtilized =(SortedSet) _inclusiveNSSet.clone();
125
					
125
					
126
		for (int i = 0; i < attrsLength; i++) {
126
		for (int i = 0; i < attrsLength; i++) {
127
			Attr N = (Attr) attrs.item(i);
127
			Attr N = (Attr) attrs.item(i);			
128
			String NName=N.getLocalName();
129
			String NNodeValue=N.getNodeValue();
128
			String NNodeValue=N.getNodeValue();
130
						
129
						
131
			if (!XMLNS_URI.equals(N.getNamespaceURI())) {
130
			if (!XMLNS_URI.equals(N.getNamespaceURI())) {
Lines 139-148 Link Here
139
				 result.add(N);				
138
				 result.add(N);				
140
				continue;
139
				continue;
141
			}
140
			}
142
	
141
			
142
			String NName=N.getLocalName();
143
			if (ns.addMapping(NName, NNodeValue,N)) {
143
			if (ns.addMapping(NName, NNodeValue,N)) {
144
				//New definition check if it is relative.
144
				//New definition check if it is relative.
145
                if (C14nHelper.namespaceIsRelative(NNodeValue)) {
145
                if (!C14nHelper.namespaceIsAbsolute(NNodeValue)) {
146
                    Object exArgs[] = {E.getTagName(), NName,
146
                    Object exArgs[] = {E.getTagName(), NName,
147
                            N.getNodeValue()};
147
                            N.getNodeValue()};
148
                    throw new CanonicalizationException(
148
                    throw new CanonicalizationException(
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 206-212 Link Here
206
	 * @param E
206
	 * @param E
207
	 * @throws CanonicalizationException
207
	 * @throws CanonicalizationException
208
	 */
208
	 */
209
	final Iterator handleAttributes(Element E, NameSpaceSymbTable ns)
209
	final Iterator handleAttributes(final Element E, final NameSpaceSymbTable ns)
210
			throws CanonicalizationException {
210
			throws CanonicalizationException {
211
		// result will contain the attrs which have to be outputted
211
		// result will contain the attrs which have to be outputted
212
		SortedSet result = new TreeSet(COMPARE);
212
		SortedSet result = new TreeSet(COMPARE);
Lines 225-232 Link Here
225
		}
225
		}
226
		
226
		
227
		for (int i = 0; i < attrsLength; i++) {
227
		for (int i = 0; i < attrsLength; i++) {
228
			Attr N = (Attr) attrs.item(i);
228
			Attr N = (Attr) attrs.item(i);			
229
			String NName=N.getLocalName();
230
			String NNodeValue=N.getNodeValue();
229
			String NNodeValue=N.getNodeValue();
231
			if ( !this._xpathNodeSet.contains(N) )  {
230
			if ( !this._xpathNodeSet.contains(N) )  {
232
				//The node is not in the nodeset(if there is a nodeset)
231
				//The node is not in the nodeset(if there is a nodeset)
Lines 247-256 Link Here
247
				continue;
246
				continue;
248
			}
247
			}
249
						
248
						
250
			
249
			String NName=N.getLocalName();
251
			if (ns.addMapping(NName, NNodeValue,N)) {
250
			if (ns.addMapping(NName, NNodeValue,N)) {
252
                //New definiton check if it is relative
251
                //New definiton check if it is relative
253
                if (C14nHelper.namespaceIsRelative(NNodeValue)) {
252
                if (!C14nHelper.namespaceIsAbsolute(NNodeValue)) {
254
                    Object exArgs[] = {E.getTagName(), NName,
253
                    Object exArgs[] = {E.getTagName(), NName,
255
                            N.getNodeValue()};
254
                            N.getNodeValue()};
256
                    throw new CanonicalizationException(
255
                    throw new CanonicalizationException(
Lines 283-289 Link Here
283
			Iterator it=visiblyUtilized.iterator();
282
			Iterator it=visiblyUtilized.iterator();
284
			while (it.hasNext()) {
283
			while (it.hasNext()) {
285
				String s=(String)it.next();										
284
				String s=(String)it.next();										
286
				Attr key=ns.getMapping(s);
285
				Attr key=(Attr)ns.getMapping(s);
287
				if (key==null) {
286
				if (key==null) {
288
					continue;
287
					continue;
289
				}
288
				}
Lines 293-299 Link Here
293
			Iterator it=this._inclusiveNSSet.iterator();
292
			Iterator it=this._inclusiveNSSet.iterator();
294
			while (it.hasNext()) {
293
			while (it.hasNext()) {
295
				String s=(String)it.next();				
294
				String s=(String)it.next();				
296
				Attr key=ns.getMappingWithoutRendered(s);
295
				Attr key=(Attr)ns.getMappingWithoutRendered(s);
297
				if (key==null) {
296
				if (key==null) {
298
					continue;
297
					continue;
299
				}
298
				}
(-)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 (-10 / +38 lines)
Lines 35-41 Link Here
35
 * and at the same time in a list so it can be removed when the frame is pop back.
35
 * and at the same time in a list so it can be removed when the frame is pop back.
36
 * @author Raul Benito
36
 * @author Raul Benito
37
 **/
37
 **/
38
public class NameSpaceSymbTable {
38
public class NameSpaceSymbTable  {
39
	
39
	
40
	/**The map betwen prefix-> entry table. */
40
	/**The map betwen prefix-> entry table. */
41
	HashMap symb = new HashMap();
41
	HashMap symb = new HashMap();
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 291-303 Link Here
291
		}	
306
		}	
292
		return ne.n;
307
		return ne.n;
293
	}
308
	}
309
    /** @inheritDoc */
310
    public NameSpaceSymbTable copyCurrent() {                 
311
            NameSpaceSymbTable nsNew=new NameSpaceSymbTable();
312
313
            Iterator it=symb.keySet().iterator();
314
            while (it.hasNext()) {
315
            	Object ob=it.next();
316
                nsNew.symb.put(ob,((NameSpaceSymbEntry)symb.get(ob)).clone());
317
            }
318
            return nsNew;            
319
    }
320
294
}
321
}
295
322
296
/**
323
/**
297
 * The internal structure of NameSpaceSymbTable.
324
 * The internal structure of NameSpaceSymbTable.
298
 **/
325
 **/
299
class NameSpaceSymbEntry implements Cloneable {
326
class NameSpaceSymbEntry implements Cloneable {
300
    NameSpaceSymbEntry(String name,Attr n,boolean rendered) {
327
    NameSpaceSymbEntry(String name,Object n,boolean rendered) {
301
        this.uri=name;          
328
        this.uri=name;          
302
        this.rendered=rendered;
329
        this.rendered=rendered;
303
        this.n=n;            
330
        this.n=n;            
Lines 310-315 Link Here
310
            return null;
337
            return null;
311
        }
338
        }
312
    }
339
    }
340
313
    /** The level where the definition was rendered(Only for inclusive) */
341
    /** The level where the definition was rendered(Only for inclusive) */
314
    int level=0;
342
    int level=0;
315
    /**The URI that the prefix defines */
343
    /**The URI that the prefix defines */
Lines 319-323 Link Here
319
    /**This prefix-URI has been already render or not.*/
347
    /**This prefix-URI has been already render or not.*/
320
    boolean rendered=false;
348
    boolean rendered=false;
321
    /**The attribute to include.*/
349
    /**The attribute to include.*/
322
    Attr n;        
350
    Object n;        
323
};
351
};
(-)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_samples/.cvsignore (+1 lines)
Added Link Here
1
prb.tgz
(-)src_samples/com/r_bg/sax_signature/EnvelopingSignatureControler.java (+106 lines)
Added Link Here
1
/*
2
 * Created on Dec 30, 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 com.r_bg.sax_signature;
8
9
import java.io.IOException;
10
11
import org.apache.xml.security.algorithms.SignatureAlgorithm;
12
import org.apache.xml.security.c14n.implementations.NameSpaceSymbTable;
13
import org.apache.xml.security.signature.XMLSignatureException;
14
import org.apache.xml.security.utils.SignerOutputStream;
15
import org.xml.sax.Attributes;
16
17
import com.r_bg.sax_signature.c14n.SaxC14nBase;
18
import com.r_bg.sax_signature.c14n.SaxC14nExcl;
19
import com.r_bg.sax_signature.c14n.SaxC14nIncl;
20
import com.r_bg.sax_signature.c14n.SaxC14nUnknown;
21
import com.r_bg.sax_signature.readers.KeyInfoReader;
22
import com.r_bg.sax_signature.readers.ReferenceReader;
23
import com.r_bg.sax_signature.readers.SignatureReader;
24
25
class EnvelopingSignatureControler extends SignatureControler implements SaxListener {
26
    SaxC14nBase sc;
27
    String uriId=null;
28
    boolean inRef=false;
29
    ReferenceReader ref=null;   
30
    /* (non-Javadoc)
31
     * @see com.r_bg.sax_signature.SignatureControler#startElement(java.lang.String, java.lang.String)
32
     */
33
    public void startElement(String uri, String localName,String qName,Attributes atrs) {
34
        if (DSIG_NS.equals(uri) && SIGNATURE.equals(localName)) {
35
            signature=new SignatureReader(this);
36
            saxHandler.add(signature);            
37
        } else if (DSIG_NS.equals(uri) && "SignedInfo".equals(localName)) {            
38
            sc=new SaxC14nUnknown();
39
            sc.ns=saxHandler.ns.copyCurrent(); 
40
            saxHandler.add(sc);
41
        } else if (!inRef && (refC14n==null) && (uriId!=null) && isId(uriId,atrs)) {            
42
            refC14n=generateSaxC14(ref);
43
            refC14n.ns= saxHandler.ns.copyCurrent();
44
            saxHandler.add(refC14n);
45
            inRef=false;
46
        }
47
        
48
    }
49
    /* (non-Javadoc)
50
     * @see com.r_bg.sax_signature.SignatureControler#endElement(java.lang.String, java.lang.String)
51
     */
52
    public void endElement(String uri, String localName) {        
53
    }
54
    
55
    public static boolean isId(String id, Attributes atrs) {
56
        if (id.equals(atrs.getValue("Id"))) {
57
            return true;
58
        }
59
        return false;
60
    }
61
    public void onReferenceReaded(ReferenceReader ref) {
62
        
63
        String uri=ref.getUri(); uri=uri.substring(1,uri.length());
64
        uriId=uri;
65
        this.ref=ref;
66
        System.err.println("Add referenece:"+uriId);
67
        
68
    }
69
    /* (non-Javadoc)
70
     * @see com.r_bg.sax_signature.SaxListener#onC14nMethodReaded()
71
     */
72
    public void onC14nMethodReaded() {
73
        String method=signature.getC14nMethod();
74
        try {
75
            //  Fix the current c14n
76
            SaxC14nBase scNew=null;
77
            if ("http://www.w3.org/TR/2001/REC-xml-c14n-20010315".equals(method)) {
78
                scNew=new SaxC14nIncl();                
79
            } else if ("http://www.w3.org/2001/10/xml-exc-c14n#".equals(method)) {
80
                scNew=new SaxC14nExcl();                
81
            }            
82
            if (scNew!=null) {                
83
                scNew.ns=sc.ns;
84
                ((SaxC14nUnknown)sc).refill(scNew);
85
                saxHandler.replace(sc,scNew);
86
                sc=scNew;                
87
            }        
88
        } catch (Exception e) {
89
            throw new RuntimeException("Error",e);
90
        }
91
    }
92
	
93
    public void onKeyInfo(KeyInfoReader key) {        
94
        try {
95
            SignatureAlgorithm sa=signature.getSignatureAlgorithm();            
96
			sa.initVerify(key.getPublicKey());
97
            sc.setOutputStream(new SignerOutputStream(sa));
98
		} catch (XMLSignatureException e) {
99
			// TODO Auto-generated catch block
100
			e.printStackTrace();
101
		}catch (IOException e) {
102
            // TODO Auto-generated catch block
103
            e.printStackTrace();
104
        }	
105
	}
106
}
(-)src_samples/com/r_bg/sax_signature/OneLevelEnvelopedSignatureControler.java (+139 lines)
Added Link Here
1
/*
2
 * Created on Jan 6, 2005
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package com.r_bg.sax_signature;
8
9
import java.io.IOException;
10
11
import org.apache.xml.security.algorithms.SignatureAlgorithm;
12
import org.apache.xml.security.c14n.implementations.NameSpaceSymbTable;
13
import org.apache.xml.security.signature.XMLSignatureException;
14
import org.apache.xml.security.utils.SignerOutputStream;
15
import org.xml.sax.Attributes;
16
import org.xml.sax.SAXException;
17
18
import com.r_bg.sax_signature.c14n.SaxC14nBase;
19
import com.r_bg.sax_signature.c14n.SaxC14nExcl;
20
import com.r_bg.sax_signature.c14n.SaxC14nIncl;
21
import com.r_bg.sax_signature.c14n.SaxC14nUnknown;
22
import com.r_bg.sax_signature.readers.KeyInfoReader;
23
import com.r_bg.sax_signature.readers.ReferenceReader;
24
import com.r_bg.sax_signature.readers.SignatureReader;
25
26
/**
27
 * @author raul
28
 *
29
 * TODO To change the template for this generated type comment go to
30
 * Window - Preferences - Java - Code Style - Code Templates
31
 */
32
public class OneLevelEnvelopedSignatureControler extends SignatureControler implements SaxListener {
33
    SaxC14nBase sc;
34
    String uriId=null;
35
    boolean inRef=false;
36
    ReferenceReader ref=null;   
37
    /* (non-Javadoc)
38
     * @see com.r_bg.sax_signature.SignatureControler#startElement(java.lang.String, java.lang.String)
39
     */
40
    public void startElement(String uri, String localName, String qName,Attributes atrs) throws SAXException {
41
        if (DSIG_NS.equals(uri) && SIGNATURE.equals(localName)) {
42
            //One Signature found the above was the reference.
43
            signature=new SignatureReader(this);
44
            saxHandler.add(signature);            
45
            inRef=true;
46
            //As is going to be enveloped stop C14n of the refC14n            
47
            saxHandler.pause(refC14n);           
48
            ((SaxC14nUnknown)refC14n).removeLastPrefixMapping();
49
        } else if (DSIG_NS.equals(uri) && "SignedInfo".equals(localName)) {            
50
            sc=new SaxC14nUnknown();
51
            sc.ns=(NameSpaceSymbTable) saxHandler.ns.copyCurrent(); 
52
            saxHandler.add(sc);
53
        } else if (!inRef) {
54
            if (refC14n!=null) {
55
            	//Just remove the before unknown c14n
56
            	saxHandler.remove(refC14n);
57
            }
58
            refC14n=new SaxC14nUnknown();
59
            refC14n.ns=(NameSpaceSymbTable) saxHandler.ns.copyCurrent();
60
            //System.out.println("NS:a="+((Object[])refC14n.ns.getMappingWithoutRendered("a"))[1]);
61
            saxHandler.add(refC14n);
62
            //refC14n.startElement(uri,localName,qName,atrs);
63
            
64
        }        
65
        
66
    }
67
    /* (non-Javadoc)
68
     * @see com.r_bg.sax_signature.SignatureControler#endElement(java.lang.String, java.lang.String)
69
     */
70
    public void endElement(String uri, String localName) {        
71
    }
72
    
73
74
    public void onReferenceReaded(ReferenceReader ref) {
75
        
76
        String uri=ref.getUri(); uri=uri.substring(1,uri.length());
77
        uriId=uri;
78
        this.ref=ref;
79
        System.err.println("Add referenece:"+uriId);        
80
        
81
    }
82
    /* (non-Javadoc)
83
     * @see com.r_bg.sax_signature.SaxListener#onC14nMethodReaded()
84
     */
85
    public void onC14nMethodReaded() {
86
        String method=signature.getC14nMethod();
87
        try {
88
            //  Fix the current c14n
89
            SaxC14nBase scNew=null;
90
            if ("http://www.w3.org/TR/2001/REC-xml-c14n-20010315".equals(method)) {
91
                scNew=new SaxC14nIncl();                
92
            } else if ("http://www.w3.org/2001/10/xml-exc-c14n#".equals(method)) {
93
                scNew=new SaxC14nExcl();                
94
            }            
95
            if (scNew!=null) {                
96
                scNew.ns=sc.ns;
97
                ((SaxC14nUnknown)sc).refill(scNew);
98
                saxHandler.replace(sc,scNew);
99
                sc=scNew;                
100
            }        
101
        } catch (Exception e) {
102
            throw new RuntimeException("Error",e);
103
        }
104
    }
105
    
106
    public void onKeyInfo(KeyInfoReader key) {        
107
        try {
108
            SignatureAlgorithm sa=signature.getSignatureAlgorithm();            
109
            sa.initVerify(key.getPublicKey());
110
            sc.setOutputStream(new SignerOutputStream(sa));
111
        } catch (XMLSignatureException e) {
112
            // TODO Auto-generated catch block
113
            e.printStackTrace();
114
        }catch (IOException e) {
115
            // TODO Auto-generated catch block
116
            e.printStackTrace();
117
        }   
118
    }
119
    
120
    /* (non-Javadoc)
121
	 * @see com.r_bg.sax_signature.SignatureControler#onRemove(com.r_bg.sax_signature.SaxWorker)
122
	 */
123
	public void onRemove(SaxWorker worker) {
124
		if (worker==signature) {
125
			//We have finish with the signature continue with the reference            
126
            saxHandler.resume(refC14n);
127
            SaxC14nBase newRefC14n=generateSaxC14(ref);            
128
            try {
129
				((SaxC14nUnknown)refC14n).refill(newRefC14n);                
130
			} catch (SAXException e) {
131
				// TODO Auto-generated catch block
132
				e.printStackTrace();
133
			}
134
            saxHandler.replace(refC14n,newRefC14n);
135
            refC14n=newRefC14n;
136
            
137
        }
138
	}
139
}
(-)src_samples/com/r_bg/sax_signature/SaxHandler.java (+127 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 2004
3
 */
4
package com.r_bg.sax_signature;
5
6
import java.util.ArrayList;
7
import java.util.Iterator;
8
9
import org.apache.xml.security.c14n.implementations.NameSpaceSymbTable;
10
import org.xml.sax.Attributes;
11
import org.xml.sax.SAXException;
12
import org.xml.sax.helpers.DefaultHandler;
13
14
/**
15
 * The main receptor of SAX Events it's main role is forward to any Worker and been controled by 
16
 * Controler
17
 * @author raul
18
 */
19
public class SaxHandler extends DefaultHandler {
20
    SignatureControler sc;
21
    int level=0;
22
    int maxLevel=-1;
23
    /** The Workers to send events */
24
    ArrayList workers=new ArrayList();
25
    ArrayList workersLevel=new ArrayList();
26
27
    ArrayList workersPause=new ArrayList();
28
    ArrayList workersLevelPause=new ArrayList();
29
    
30
    NameSpaceSymbTable ns=new NameSpaceSymbTable();
31
    
32
    protected SaxHandler(SignatureControler sc) {
33
    	this.sc=sc;        
34
    }
35
    /**
36
     * A new thing.
37
     */
38
    public void startElement(String uri, String localName, String qName, Attributes attributes) 
39
    throws SAXException {
40
        ns.push();
41
        level++;
42
        //Let the Sc add things add needed
43
        sc.startElement(uri,localName,qName, attributes);
44
        Iterator it=workers.iterator();
45
        while (it.hasNext()) {
46
        	((SaxWorker)it.next()).startElement(uri,localName,qName,attributes); 
47
        }        
48
    }
49
50
    public void characters(char[] ch, int start, int length) throws SAXException{
51
        Iterator it=workers.iterator();
52
        while (it.hasNext()) {
53
            ((SaxWorker)it.next()).characters(ch,start,length); 
54
        } 
55
    }
56
57
    public void endElement(String uri, String localName, String qName) throws SAXException {
58
        level--;
59
        ns.pop();  
60
        //Let the sc remove workers
61
        sc.endElement(uri,localName);        
62
        Iterator it=((ArrayList)(workers.clone())).iterator();
63
        while (it.hasNext()) {
64
            ((SaxWorker)it.next()).endElement(uri,localName,qName); 
65
        }
66
67
        //Now remove the ones that go up the level.
68
        if (maxLevel>level) {
69
            //System.out.println("Looking for remove:"+maxLevel);
70
            maxLevel=-1;
71
        	it=((ArrayList)(workersLevel.clone())).iterator();
72
        	int i=0;
73
        	while (it.hasNext()) {
74
        		int levelC=((Integer)it.next()).intValue();
75
        		if (levelC>level) {
76
        			Object ob=workers.remove(i);
77
        			workersLevel.remove(i);
78
        			sc.onRemove((SaxWorker)ob);
79
        		} else {
80
                    maxLevel=maxLevel<level?level:maxLevel;
81
        			i++;
82
        		}
83
        	}
84
        }
85
        
86
    }
87
        
88
	public void startPrefixMapping(String prefix, String uri)
89
			throws SAXException {
90
        String realPrefix=("".equals(prefix) ? "xmlns" : prefix);
91
        String []attr = {"xmlns"
92
                ,uri,("".equals(prefix) ? "xmlns" : "xmlns:"+prefix)};
93
        ns.addMapping(realPrefix,uri,attr);
94
        Iterator it=workers.iterator();
95
        while (it.hasNext()) {
96
            ((SaxWorker)it.next()).startPrefixMapping(prefix,uri); 
97
        } 
98
	}
99
100
    public void add(SaxWorker worker) {
101
        maxLevel=level;
102
    	workers.add(0,worker);
103
        workersLevel.add(0,new Integer(level));
104
    }
105
    public void replace(SaxWorker old,SaxWorker newW) {
106
    	int pos=workers.indexOf(old);
107
        workers.set(pos,newW);
108
    }
109
    public void remove(SaxWorker worker) {
110
        int pos=workers.indexOf(worker);
111
        workers.remove(worker);
112
        workersLevel.remove(pos);
113
    }
114
    public void pause(SaxWorker worker) {
115
    	int pos=workers.indexOf(worker);
116
        workers.remove(worker);
117
        workersPause.add(worker);
118
        workersLevelPause.add(workersLevel.remove(pos));        
119
    }
120
 
121
    public void resume(SaxWorker worker) {
122
    	int pos=workersPause.indexOf(worker);
123
        workersPause.remove(worker);
124
        workers.add(worker);
125
        workersLevel.add(workersLevelPause.remove(pos));
126
    }
127
}
(-)src_samples/com/r_bg/sax_signature/SaxListener.java (+25 lines)
Added Link Here
1
/*
2
 * Created on Dec 19, 2004
3
 */
4
package com.r_bg.sax_signature;
5
6
import com.r_bg.sax_signature.readers.KeyInfoReader;
7
import com.r_bg.sax_signature.readers.ReferenceReader;
8
9
/**
10
 * @author raul
11
 *
12
 */
13
public interface SaxListener {
14
	public void onReferenceReaded(ReferenceReader ref);
15
16
	/**
17
	 * 
18
	 */
19
	public void onC14nMethodReaded();
20
21
	/**
22
	 * @param key
23
	 */
24
	public void onKeyInfo(KeyInfoReader key);
25
}
(-)src_samples/com/r_bg/sax_signature/SaxWorker.java (+13 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 2004
3
 */
4
package com.r_bg.sax_signature;
5
6
import org.xml.sax.helpers.DefaultHandler;
7
8
/**
9
 * The Base class for the other people.
10
 */
11
public class SaxWorker extends DefaultHandler {
12
13
}
(-)src_samples/com/r_bg/sax_signature/SignatureControler.java (+101 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 2004
3
 */
4
package com.r_bg.sax_signature;
5
6
import java.io.IOException;
7
import java.security.PublicKey;
8
9
import org.xml.sax.Attributes;
10
import org.xml.sax.SAXException;
11
12
13
import com.r_bg.sax_signature.c14n.SaxC14nBase;
14
import com.r_bg.sax_signature.c14n.SaxC14nExcl;
15
import com.r_bg.sax_signature.c14n.SaxC14nIncl;
16
import com.r_bg.sax_signature.readers.ReferenceReader;
17
import com.r_bg.sax_signature.readers.SignatureReader;
18
19
/**
20
 * Controls the creation of SaxReaders. Possible Interface
21
 * TODO: Only one signature per document right now.
22
 * @author raul
23
 */
24
public  class SignatureControler {
25
    /** The Handler we are associated to */
26
    SaxHandler saxHandler;
27
    /** The signature object we are working on */
28
    SignatureReader signature;
29
    protected SaxC14nBase refC14n;
30
    
31
    public final static String DSIG_NS="http://www.w3.org/2000/09/xmldsig#";
32
    public final static String SIGNATURE="Signature";
33
    /**
34
     * Creates a signature mediator
35
     */
36
    public SignatureControler() {
37
        
38
    }
39
    
40
    public SaxHandler createSaxHandler() {
41
        saxHandler=new SaxHandler(this);
42
        return saxHandler;
43
    }
44
    /**
45
     * New Element processed. Before sending to the Workers. It can add new Workers.
46
     * @param uri
47
     * @param localName
48
     */
49
	public void startElement(String uri, String localName, String qName, Attributes atr) throws SAXException {
50
        if (DSIG_NS.equals(uri) && SIGNATURE.equals(localName)) {
51
            signature=new SignatureReader((PublicKey)null);
52
            saxHandler.add(signature);
53
        }
54
    }
55
    public void endElement(String uri, String localName) {
56
    }
57
    public boolean verifyReference(int number) {
58
    	assert number!=0 : "Only one reference, sorry";
59
        String expected=signature.getReference(number).getDigestValue();
60
        String obtained=refC14n.getBase64Digest();
61
        if (!expected.equals(obtained)) {
62
        	//Log error & return            
63
            System.err.println("Error expected:"+expected+" but got:"+obtained);
64
            return false;
65
        }
66
        return true;
67
        
68
    }
69
70
	public boolean verify() {        
71
		return signature.validateSignature();
72
	}
73
74
	/**
75
	 * @param worker
76
	 */
77
	public void onRemove(SaxWorker worker) {
78
	}
79
80
	/**
81
	 * @param ref2
82
	 * @return
83
	 */
84
	protected static SaxC14nBase generateSaxC14(ReferenceReader ref2) {
85
	    SaxC14nBase sol;
86
	    if (ref2.isExclusive()) {
87
	        sol=new SaxC14nExcl();
88
	    } else {
89
	       sol=new SaxC14nIncl();
90
	    }
91
        
92
	    try {
93
			sol.setOutputStream( ref2.getDigesterOutput());
94
		} catch (IOException e) {
95
			throw new RuntimeException("Unable to set OutputStream",e);
96
		}
97
	    return sol;
98
	}
99
100
}
101
(-)src_samples/com/r_bg/sax_signature/c14n/AttributesCompare.java (+88 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.c14n;
8
9
/**
10
 * @author raul
11
 *
12
 * TODO To change the template for this generated type comment go to
13
 * Window - Preferences - Java - Code Style - Code Templates
14
 */
15
class AttributesCompare implements java.util.Comparator {
16
    /* (non-Javadoc)
17
     * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
18
     */
19
    public int compare(Object obj0, Object obj1) {
20
         String[] attr0 = (String[]) obj0;
21
           String[] attr1 = (String[]) obj1;
22
          String namespaceURI0 = attr0[0];      
23
          String namespaceURI1 = attr1[0];
24
          
25
          boolean isNamespaceAttr0 =
26
             "xmlns".equals(namespaceURI0);
27
          boolean isNamespaceAttr1 =
28
             "xmlns".equals(namespaceURI1);
29
30
          if (isNamespaceAttr0) {
31
             if (isNamespaceAttr1) {
32
33
                // both are namespaces
34
                String localname0 = attr0[1];
35
                String localname1 = attr1[1];
36
37
                if (localname0.equals("xmlns")) {
38
                   localname0 = "";
39
                }
40
41
                if (localname1.equals("xmlns")) {
42
                   localname1 = "";
43
                }
44
45
                return localname0.compareTo(localname1);
46
             }
47
             // attr0 is a namespace, attr1 is not
48
             return -1;
49
             
50
          } 
51
          if (isNamespaceAttr1) {
52
53
                // attr1 is a namespace, attr0 is not
54
                return +1;
55
          } 
56
57
          // none is a namespae
58
          
59
          if (namespaceURI0 == null) {
60
            if (namespaceURI1 == null) {
61
                /*
62
                 String localName0 = attr0.getLocalName();
63
                 String localName1 = attr1.getLocalName();
64
                 return localName0.compareTo(localName1);
65
                 */
66
                
67
                String name0 = attr0[1];
68
                String name1 = attr1[1];
69
                return name0.compareTo(name1);
70
            }
71
            return -1;
72
            
73
          } 
74
          if (namespaceURI1 == null) {
75
                return +0;
76
          } 
77
          int a = namespaceURI0.compareTo(namespaceURI1);
78
                
79
          if (a != 0) {
80
            return a;
81
          }
82
          
83
          String localName0 = attr0[2];
84
          String localName1 = attr1[2];
85
          
86
          return localName0.compareTo(localName1);
87
    }
88
}
(-)src_samples/com/r_bg/sax_signature/c14n/SaxC14nBase.java (+200 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.c14n;
8
9
import java.io.ByteArrayOutputStream;
10
import java.io.IOException;
11
import java.io.OutputStream;
12
import java.util.Iterator;
13
import java.util.SortedSet;
14
15
import org.apache.xml.security.c14n.implementations.NameSpaceSymbTable;
16
import org.apache.xml.security.utils.Base64;
17
import org.apache.xml.security.utils.DigesterOutputStream;
18
import org.apache.xml.security.utils.SignerOutputStream;
19
import org.xml.sax.Attributes;
20
import org.xml.sax.SAXException;
21
22
import com.r_bg.sax_signature.SaxWorker;
23
24
/**
25
 * @author raul
26
 *
27
 * TODO To change the template for this generated type comment go to
28
 * Window - Preferences - Java - Code Style - Code Templates
29
 */
30
public abstract class SaxC14nBase extends SaxWorker{
31
    public NameSpaceSymbTable ns=null;
32
33
    private boolean outputComments=true;
34
    public OutputStream os=new ByteArrayOutputStream();    
35
    
36
    /** @throws IOException
37
     * @inheritDoc **/
38
    final static byte[] EQ_Q= {'=','"'};
39
    final static byte[] END_T= {'<','/'};
40
    public void startElement(String arg0, String arg1, String arg2, Attributes arg3)
41
        throws SAXException {                
42
        ns.push();
43
        SortedSet s = handleAttributes(arg2, arg3);
44
        try {
45
        os.write('<');
46
        writeStringToUtf8(arg2,os);
47
        Iterator it=s.iterator();
48
        while (it.hasNext()) {
49
            String[] attr=(String[])it.next();
50
            os.write(' ');writeStringToUtf8(attr[2],os);
51
            os.write(EQ_Q);
52
            writeStringToUtf8(attr[1],os);
53
            os.write('"');
54
        }
55
        os.write('>');
56
        } catch (IOException e) {
57
            throw new RuntimeException(e);
58
        }
59
    }
60
    public void setNamespaceTable(NameSpaceSymbTable ns) {
61
    	this.ns=ns;
62
    }
63
    abstract SortedSet handleAttributes(String arg2, Attributes arg3);
64
    /** @inheritDoc **/
65
    public void characters(char[] arg0, int arg1, int arg2) {
66
        try {
67
            for (int i=arg1;i<arg1+arg2;i++)       
68
                writeCharToUtf8(arg0[i],os);
69
        } catch (IOException e) { 
70
            throw new RuntimeException(e);
71
        }
72
    }
73
    
74
    /** @inheritDoc **/
75
    public void startPrefixMapping(String arg0, String arg1)
76
            throws SAXException {        
77
        String prefix=("".equals(arg0) ? "xmlns" : arg0);
78
        String []attr = {"xmlns"
79
                ,arg1,("".equals(arg0) ? "xmlns" : "xmlns:"+arg0)};
80
        ns.addMapping(prefix,arg1,attr);
81
    }
82
    
83
    /** @inheritDoc **/
84
    public void endElement(String arg0, String arg1, String arg2)
85
            throws SAXException {
86
        try {
87
        os.write(END_T);
88
        writeStringToUtf8(arg2,os);
89
        os.write('>');
90
        } catch (IOException e) {
91
            throw new RuntimeException(e);   
92
        }
93
        ns.pop();
94
95
    }
96
    
97
    /** @inheritDoc **/
98
    public void endCDATA() {
99
        
100
    }
101
    
102
    /** @inheritDoc **/
103
    public void endDTD() {
104
        
105
    }
106
    
107
    /** @inheritDoc **/
108
    public void startCDATA(){
109
        
110
    }
111
    
112
    /** @inheritDoc **/
113
    public void comment(char[] arg0, int arg1, int arg2) {
114
        if (!outputComments) {
115
            return;
116
        }
117
        String st=new String(arg0,arg1,arg2);
118
        try {
119
            os.write(("<!--"+st+"-->").getBytes());
120
        } catch (IOException e) {
121
            throw new RuntimeException(e);   
122
        }
123
    }
124
    final static void writeCharToUtf8(char c,OutputStream out) throws IOException{
125
        
126
        if (/*(c >= 0x0001) &&*/ (c <= 0x007F)) {
127
            out.write(c);
128
        } else if (c > 0x07FF) {
129
            out.write(0xE0 | ((c >> 12) & 0x0F));
130
            out.write(0x80 | ((c >>  6) & 0x3F));
131
            out.write(0x80 | ((c >>  0) & 0x3F));
132
            
133
        } else {
134
            out.write(0xC0 | ((c >>  6) & 0x1F));
135
            out.write(0x80 | ((c >>  0) & 0x3F));
136
            
137
        }
138
        
139
       }
140
    
141
    /** @inheritDoc **/
142
    public void endEntity(String arg0)  {
143
        
144
    }
145
    
146
    /** @inheritDoc **/
147
    public void startEntity(String arg0)  {
148
        
149
    }
150
    
151
    /** @inheritDoc **/
152
    public void startDTD(String arg0, String arg1, String arg2)  {  
153
    }
154
    final static void writeStringToUtf8(String str,OutputStream out) throws IOException{
155
        int length=str.length();
156
        for (int i=0;i<length;i++) {
157
            char c=str.charAt(i);
158
            if (/*(c >= 0x0001) && */(c <= 0x007F)) {
159
                out.write(c);
160
            } else if (c > 0x07FF) {
161
                out.write(0xE0 | ((c >> 12) & 0x0F));
162
                out.write(0x80 | ((c >>  6) & 0x3F));
163
                out.write(0x80 | ((c >>  0) & 0x3F));
164
                
165
            } else {
166
                out.write(0xC0 | ((c >>  6) & 0x1F));
167
                out.write(0x80 | ((c >>  0) & 0x3F));
168
                
169
            }
170
        }
171
    }
172
173
    /**
174
     * @param md
175
     * @throws IOException
176
     */
177
    public void setOutputStream(OutputStream md) throws IOException {
178
        md.write(((ByteArrayOutputStream)os).toByteArray());
179
        os=md;
180
    }
181
182
    
183
    public String getBase64Digest() {
184
        try {
185
            os.flush();
186
        } catch (IOException e) {
187
            // TODO Auto-generated catch block
188
            e.printStackTrace();
189
        }
190
        if (os instanceof DigesterOutputStream)
191
        return Base64.encode(((DigesterOutputStream)os).getDigestValue());
192
        
193
        return null;
194
    }
195
    public boolean verifySignature(byte[] a) {
196
        if (os instanceof SignerOutputStream)
197
            return ((SignerOutputStream)os).verify(a); 
198
        return false;
199
    }
200
}
(-)src_samples/com/r_bg/sax_signature/c14n/SaxC14nExcl.java (+64 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.c14n;
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
/**
17
 * @author raul
18
 *
19
 * TODO To change the template for this generated type comment go to
20
 * Window - Preferences - Java - Code Style - Code Templates
21
 */
22
public class SaxC14nExcl extends SaxC14nBase {    
23
        /**
24
         * @param arg2
25
         * @param arg3
26
         * @return
27
         */
28
        SortedSet handleAttributes(String arg2, Attributes arg3) {
29
            SortedSet visiblyUtilized =new TreeSet();        
30
            SortedSet s=new TreeSet(new AttributesCompare());
31
            for (int i=0;i<arg3.getLength();i++) {
32
                String qname=arg3.getQName(i);
33
                int colon=qname.indexOf(':');            
34
                String prefix=qname;
35
                if (colon>0) {
36
                    prefix=qname.substring(0,colon);                
37
                } 
38
                if (!"xml".equals(prefix)) {
39
                    visiblyUtilized.add(prefix);
40
                }            
41
                String []attr= {arg3.getURI(i),arg3.getValue(i),qname};
42
                s.add(attr);                        
43
            }
44
            int colon=arg2.indexOf(':');
45
            String prefix=null;
46
            if (colon>0) {            
47
               prefix=arg2.substring(0,arg2.indexOf(':'));                     
48
               visiblyUtilized.add(prefix);
49
            } else {
50
                visiblyUtilized.add("xmlns");
51
            }
52
            Iterator it=visiblyUtilized.iterator();
53
            while (it.hasNext()) {
54
                String prefix1=(String)it.next();                                 
55
                String[] key=(String [])ns.getMapping(prefix1);
56
                if (key==null) {
57
                    continue;
58
                }
59
                s.add(key);
60
            }
61
            return s;
62
        }
63
    }
64
(-)src_samples/com/r_bg/sax_signature/c14n/SaxC14nIncl.java (+34 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.c14n;
8
9
import java.util.SortedSet;
10
import java.util.TreeSet;
11
12
import org.xml.sax.Attributes;
13
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 SaxC14nIncl extends SaxC14nBase {
22
23
    SortedSet handleAttributes(String arg2, Attributes arg3) {
24
        SortedSet s=new TreeSet(new AttributesCompare());
25
        for (int i=0;i<arg3.getLength();i++) {
26
            String qname=arg3.getQName(i);          
27
            String []attr= {arg3.getURI(i),arg3.getValue(i),qname};
28
            s.add(attr);                        
29
        }
30
        ns.getUnrenderedNodes(s);
31
        return s;
32
    }
33
34
}
(-)src_samples/com/r_bg/sax_signature/c14n/SaxC14nUnknown.java (+120 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.c14n;
8
9
import java.io.IOException;
10
import java.io.OutputStream;
11
import java.util.ArrayList;
12
import java.util.Iterator;
13
import java.util.List;
14
import java.util.SortedSet;
15
16
import org.xml.sax.Attributes;
17
import org.xml.sax.SAXException;
18
import org.xml.sax.helpers.AttributesImpl;
19
20
/**
21
 * @author raul
22
 *
23
 * TODO To change the template for this generated type comment go to
24
 * Window - Preferences - Java - Code Style - Code Templates
25
 */
26
public class SaxC14nUnknown extends SaxC14nBase{
27
    OutputStream os=null;
28
    private static final Integer ENDELEMENT = new Integer(0);
29
    private static final Integer STARTPREFIXMAPPING = new Integer(1);
30
    private static final Integer CHARACTERS = new Integer(2);
31
    private static final Integer STARTELEMENT = new Integer(3);
32
    List storedEvents=new ArrayList();
33
    public void startElement(String arg0, String arg1, String arg2, Attributes arg3)
34
    throws SAXException {                
35
        storedEvents.add(STARTELEMENT);
36
        AttributesImpl atr=new AttributesImpl();
37
        for (int i=0;i<arg3.getLength();i++) {
38
            atr.addAttribute(arg3.getURI(i),arg3.getLocalName(i),arg3.getQName(i),
39
                    arg3.getType(i),arg3.getValue(i));
40
        }
41
        storedEvents.add(new Object[]{arg0,arg1,arg2,atr});
42
    }
43
    /** @inheritDoc **/
44
    public void characters(char[] arg0, int arg1, int arg2) {
45
        storedEvents.add(CHARACTERS);       
46
        storedEvents.add(new String(arg0,arg1,arg2));
47
    }
48
49
    /* (non-Javadoc)
50
     * @see prb.SaxCanon#startPrefixMapping(java.lang.String, java.lang.String)
51
     */
52
    public void startPrefixMapping(String arg0, String arg1) throws SAXException {
53
        storedEvents.add(STARTPREFIXMAPPING);
54
        storedEvents.add(new String[]{arg0, arg1});
55
    }
56
    public void removeLastPrefixMapping() {
57
        int size=storedEvents.size()-2;
58
    	if (storedEvents.get(size)!=STARTPREFIXMAPPING) {
59
    		throw new RuntimeException("PROBLEM");
60
        }
61
        storedEvents.remove(size);
62
        storedEvents.remove(size);
63
    }
64
    /** @inheritDoc **/
65
    public void endElement(String arg0, String arg1, String arg2)
66
        throws SAXException {
67
        storedEvents.add(ENDELEMENT);
68
        storedEvents.add(new String[]{arg0,arg1,arg2});
69
    }
70
    SortedSet handleAttributes(String arg2, Attributes arg3) {
71
        // TODO Auto-generated method stub
72
        return null;
73
    }
74
    
75
    public void refill(SaxC14nBase sc) throws SAXException {
76
        //Fill with the first ns.
77
        sc.setNamespaceTable(ns);
78
        if (os!=null) {
79
            try {
80
                sc.setOutputStream(os);
81
            } catch (IOException e) {
82
                // TODO Auto-generated catch block
83
                e.printStackTrace();
84
            }
85
        }
86
        Iterator it=storedEvents.iterator();
87
        while (it.hasNext()) {
88
            int type=((Integer)it.next()).intValue();  
89
            //System.out.println("TYPE:"+type);
90
            switch (type) {
91
                case 0: //endElement                
92
                    String ob[]=(String[])it.next();
93
                    sc.endElement(ob[0],ob[1],ob[2]);
94
                    break;
95
                case 1:
96
                    ob=(String[])it.next();
97
                    sc.startPrefixMapping(ob[0],ob[1]);
98
                    break;
99
                case 2:
100
                    String a=(String)it.next();
101
                    sc.characters(a.toCharArray(),0,a.length());
102
                    break;
103
                case 3:
104
                    Object ob1[]=(Object[])it.next();
105
                    //System.out.println("StartElement:"+ob1[1]);
106
                    sc.startElement((String)ob1[0],(String)ob1[1],(String)ob1[2],
107
                            (Attributes) ob1[3]);
108
                    break;                  
109
            }
110
        }
111
        
112
    }
113
    /* (non-Javadoc)
114
     * @see prb.SaxCanon#setOutputStream(java.io.OutputStream)
115
     */
116
    public void setOutputStream(OutputStream md) throws IOException {
117
        os=md;
118
    }
119
120
}
(-)src_samples/com/r_bg/sax_signature/readers/KeyInfoReader.java (+107 lines)
Added Link Here
1
/*
2
 * Created on Jan 2, 2005
3
 *
4
 * TODO To change the template for this generated file go to
5
 * Window - Preferences - Java - Code Style - Code Templates
6
 */
7
package com.r_bg.sax_signature.readers;
8
9
import java.io.ByteArrayInputStream;
10
import java.math.BigInteger;
11
import java.security.KeyFactory;
12
import java.security.NoSuchAlgorithmException;
13
import java.security.PublicKey;
14
import java.security.cert.CertificateException;
15
import java.security.cert.CertificateFactory;
16
import java.security.cert.X509Certificate;
17
import java.security.spec.InvalidKeySpecException;
18
import java.security.spec.RSAPublicKeySpec;
19
20
import org.apache.xml.security.exceptions.Base64DecodingException;
21
import org.apache.xml.security.exceptions.XMLSecurityException;
22
import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
23
import org.apache.xml.security.utils.Base64;
24
import org.xml.sax.Attributes;
25
import org.xml.sax.SAXException;
26
27
import com.r_bg.sax_signature.SaxWorker;
28
29
/**
30
 * @author raul
31
 *
32
 * TODO Make more standard compliant. Only RSA private key
33
 */
34
public class KeyInfoReader extends SaxWorker{    
35
    String modulus;
36
    String exponent;
37
    String x509Certificate;
38
    StringBuffer working=new StringBuffer();
39
    PublicKey pk;
40
    public void startElement(String uri, String localname, String arg2,
41
			Attributes arg3) throws SAXException {
42
    	if (("Modulus".equals(localname)) || "Exponent".equals(localname) || "X509Certificate".equals(localname)) {
43
    		working=new StringBuffer();
44
        }
45
        
46
	}
47
    public void endElement(String uri, String localname, String arg2)
48
			throws SAXException {
49
        if ("Modulus".equals(localname)) {
50
            modulus=working.toString();
51
            working=null;
52
        } else if ("Exponent".equals(localname)) {
53
            exponent=working.toString();
54
            working=null;
55
            try {
56
            	KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
57
            	RSAPublicKeySpec rsaKeyspec = new RSAPublicKeySpec(
58
                        new BigInteger(Base64.decode(modulus)),
59
                        new BigInteger(Base64.decode(exponent)));
60
            	setPublicKey(rsaFactory.generatePublic(rsaKeyspec));               
61
            } catch (NoSuchAlgorithmException e) {
62
				// TODO Auto-generated catch block
63
				e.printStackTrace();
64
			} catch (InvalidKeySpecException e) {
65
				// TODO Auto-generated catch block
66
				e.printStackTrace();
67
			} catch (Base64DecodingException e) {
68
				// TODO Auto-generated catch block
69
				e.printStackTrace();
70
			}
71
        } else if ("X509Certificate".equals(localname)) {
72
            x509Certificate=working.toString();
73
            working=null;
74
            try {
75
                byte certbytes[] = Base64.decode(x509Certificate.getBytes());
76
                CertificateFactory certFact =
77
                   CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
78
                X509Certificate cert =
79
                   (X509Certificate) certFact
80
                      .generateCertificate(new ByteArrayInputStream(certbytes));
81
                setPublicKey(cert.getPublicKey());
82
             } catch (CertificateException ex) {
83
             	ex.printStackTrace();
84
             } catch (Base64DecodingException e) {
85
				// TODO Auto-generated catch block
86
				e.printStackTrace();
87
			}
88
        }
89
90
    }
91
    /* (non-Javadoc)
92
	 * @see org.xml.sax.helpers.DefaultHandler#characters(char[], int, int)
93
	 */
94
	public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
95
		if (working!=null) 
96
            working.append(arg0,arg1,arg2);
97
	}
98
	public PublicKey getPublicKey() {
99
		return pk;
100
    }
101
    private void setPublicKey(PublicKey pk) {
102
        if ((this.pk!=null) && !this.pk.equals(pk)) {
103
            throw new RuntimeException("Certificate and already public key not equal.");
104
        }   
105
        this.pk=pk;
106
    }
107
}
(-)src_samples/com/r_bg/sax_signature/readers/ReferenceReader.java (+121 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.readers;
8
9
import java.io.OutputStream;
10
import java.security.MessageDigest;
11
12
import org.apache.xml.security.algorithms.JCEMapper;
13
import org.apache.xml.security.utils.Base64;
14
import org.apache.xml.security.utils.DigesterOutputStream;
15
import org.xml.sax.Attributes;
16
17
import com.r_bg.sax_signature.SaxWorker;
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 ReferenceReader extends SaxWorker{
26
       String uri;
27
       boolean inDigest=false;
28
       String digestValue;       
29
       DigesterOutputStream di;
30
       boolean exclusive=false;
31
       boolean enveloped=false;
32
       public ReferenceReader(Attributes atrs) {
33
          uri=atrs.getValue("URI");          
34
       }
35
       public void startElement(String uri,String localname,String qname,Attributes arg3) {
36
             if ("Transform".equals(localname)) {
37
                String algoth=arg3.getValue("Algorithm");
38
                if ("http://www.w3.org/2001/10/xml-exc-c14n#".
39
                        equals(algoth)) {                    
40
                    exclusive=true;                                    
41
                } else if ("http://www.w3.org/TR/2001/REC-xml-c14n-20010315".
42
                        equals(algoth)){
43
                    exclusive=false;
44
                } else if ("http://www.w3.org/2000/09/xmldsig#enveloped-signature".equals(algoth)){
45
                    enveloped=true;
46
                } else { 
47
                    throw new RuntimeException("Sorry unknown transformation:"+algoth);
48
                }
49
             }
50
             if ("DigestMethod".equals(localname)) {
51
                String algorithmURI=arg3.getValue("Algorithm");
52
                 String algorithmID = JCEMapper.translateURItoJCEID(algorithmURI);              
53
54
                 MessageDigest md;
55
56
                 try {
57
                    md = MessageDigest.getInstance(algorithmID);
58
                 } catch (java.security.NoSuchAlgorithmException ex) {
59
                    Object[] exArgs = { algorithmID,
60
                                        ex.getLocalizedMessage() };
61
62
                    throw new RuntimeException("No such algorithm");
63
                 }
64
                 this.di=new DigesterOutputStream(md);
65
                 //try {
66
                   // sc.setOutputStream(new BufferedOutputStream(di));
67
                //} catch (IOException e) {
68
                    // TODO Auto-generated catch block
69
                  //  e.printStackTrace();
70
                //}
71
                 
72
             }
73
             if ("DigestValue".equals(localname)) {
74
                inDigest=true;
75
             }
76
       }
77
       public boolean validate() {
78
        /*
79
        try {
80
            //sc.os.flush();
81
        } catch (IOException e) {
82
83
        }*/
84
            boolean b=digestValue.equals(Base64.encode(di.getDigestValue()));
85
            if (!b) {
86
                //System.out.println("fail the value:"+sc.getBase64Digest());
87
            }
88
            return b;
89
       }
90
       public void characters(char[] arg0, int arg1, int arg2) {
91
          if (inDigest) {
92
            //System.out.println("Setting digest:"+value);
93
            digestValue=new String(arg0,arg1,arg2);
94
          }
95
       }
96
       public void endElement(String uri,String localname,String qname) {
97
            if ("DigestValue".equals(localname)) {
98
                inDigest=false;
99
            }
100
       }
101
	/**
102
	 * @return Returns the uri.
103
	 */
104
	public String getUri() {
105
		return uri;
106
	}
107
	/**
108
	 * @return
109
	 */
110
	public boolean isExclusive() {
111
		return exclusive;
112
	}
113
    
114
    public String getDigestValue() {
115
    	return digestValue;
116
    }
117
    
118
   public OutputStream getDigesterOutput() {
119
   	    return di;
120
   }
121
}
(-)src_samples/com/r_bg/sax_signature/readers/SignatureReader.java (+170 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature.readers;
8
9
import java.security.PublicKey;
10
11
import org.apache.xml.security.algorithms.SignatureAlgorithm;
12
import org.apache.xml.security.exceptions.XMLSecurityException;
13
import org.apache.xml.security.signature.XMLSignatureException;
14
import org.apache.xml.security.utils.Base64;
15
import org.apache.xml.security.utils.SignerOutputStream;
16
import org.xml.sax.Attributes;
17
import org.xml.sax.SAXException;
18
19
import com.r_bg.sax_signature.SaxListener;
20
import com.r_bg.sax_signature.SaxWorker;
21
22
23
/**
24
 * @author raul
25
 *
26
 * TODO To change the template for this generated type comment go to
27
 * Window - Preferences - Java - Code Style - Code Templates
28
 */
29
public class SignatureReader extends SaxWorker {
30
    SaxWorker currentReader=null;
31
    private static final String XMLNS_URI = "http://www.w3.org/2000/09/xmldsig#";    
32
    boolean inSignatureValue=false;    
33
    String c14nMethod;
34
    ReferenceReader ref;
35
    KeyInfoReader key;
36
    String signatureValue=null;
37
    PublicKey pk;
38
    private SignatureAlgorithm sa;
39
    SaxListener listener=null;
40
    /**
41
     * 
42
     */
43
    public SignatureReader(PublicKey pk) {
44
        this.pk=pk;        
45
    }
46
    public SignatureReader(SaxListener listener) {
47
        this.listener=listener;        
48
    }
49
    
50
    /* (non-Javadoc)
51
     * @see org.xml.sax.helpers.DefaultHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
52
     */
53
    public void startElement(String arg0, String arg1, String arg2,
54
            Attributes arg3) throws SAXException {
55
        
56
        if (XMLNS_URI.equals(arg0) && "Reference".equals(arg1)) {
57
            assert ref==null : "Only one reference implemented";            
58
            //gives time to create a CannonWatch in case it isn't already created            
59
            ref=new ReferenceReader(arg3);
60
            currentReader=ref;
61
        } else 
62
        if (XMLNS_URI.equals(arg0) && "SignatureValue".equals(arg1)) {
63
            inSignatureValue=true;
64
        } else
65
        if (XMLNS_URI.equals(arg0) && "SignatureMethod".equals(arg1)) {
66
            updateSignatureStream(arg3);
67
        } else
68
        if (XMLNS_URI.equals(arg0) && "CanonicalizationMethod".equals(arg1)) {
69
            c14nMethod=arg3.getValue("Algorithm");
70
            //sd.fireOnCanonicalizationMethod(arg3);
71
        } else if (XMLNS_URI.equals(arg0) && "KeyInfo".equals(arg1)) {
72
            key=new KeyInfoReader();
73
            currentReader=key;
74
        }
75
        else
76
        if (currentReader!=null) {
77
            currentReader.startElement(arg0,arg1,arg2,arg3);
78
        }
79
    }
80
    
81
    /**
82
	 * @param arg3
83
	 */
84
	private void fireOnReference(ReferenceReader r) {
85
		listener.onReferenceReaded(r);
86
		
87
	}
88
89
	/**
90
     * @param arg3
91
     */
92
    private void updateSignatureStream(Attributes arg3) {
93
        try {
94
            sa = new SignatureAlgorithm(arg3.getValue("Algorithm"));                        
95
        } catch (XMLSecurityException e) {
96
            throw new RuntimeException("No algoth",e);
97
        }
98
    }
99
100
    public void endElement(String arg0, String arg1, String arg2)
101
            throws SAXException {
102
        if (XMLNS_URI.equals(arg0) && "CanonicalizationMethod".equals(arg1)) {         
103
            fireOnCanonicalizationMethod();
104
        } else
105
        if (XMLNS_URI.equals(arg0) && "Reference".equals(arg1)) {
106
            currentReader=null;   
107
            fireOnReference(ref);
108
        } else
109
        if (XMLNS_URI.equals(arg0) && "SignatureValue".equals(arg1)) {
110
            inSignatureValue=false;
111
        } else if (XMLNS_URI.equals(arg0) && "KeyInfo".equals(arg1)) {
112
            fireOnKeyInfo();
113
            currentReader=null;
114
        }else
115
        if (currentReader!=null) {
116
            currentReader.endElement(arg0,arg1,arg2);
117
        }        
118
    }
119
    /**
120
	 * 
121
	 */
122
	private void fireOnCanonicalizationMethod() {
123
		listener.onC14nMethodReaded();
124
		
125
	}
126
    private void fireOnKeyInfo() {
127
    	listener.onKeyInfo(key);
128
    }
129
	public boolean validateReferences() {       
130
        return ref.validate();
131
    }
132
    
133
    public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
134
        if (currentReader!=null) {
135
            currentReader.characters(arg0,arg1,arg2);
136
        }
137
        if (inSignatureValue) {
138
            if (signatureValue!=null)
139
                signatureValue+=new String(arg0,arg1,arg2);
140
            else
141
                signatureValue=new String(arg0,arg1,arg2);
142
        }
143
    }
144
    
145
    public boolean validateSignature() {
146
        //System.out.println("a="+signatureValue);
147
        try {
148
            //((CanonWatch)sd.scs.get(0)).sc.os.flush();
149
            return sa.verify(Base64.decode(signatureValue));
150
        } catch (Exception e) {
151
            throw new RuntimeException(e);
152
        }       
153
    }
154
	/**
155
	 * @return
156
	 */
157
	public String getC14nMethod() {
158
		return c14nMethod;
159
	}
160
    
161
    public ReferenceReader getReference(int i) {
162
      assert i==0: "More than one";
163
      return ref;
164
    }
165
166
    public SignatureAlgorithm getSignatureAlgorithm() {
167
    	return sa;
168
    }
169
170
}
(-)src_unitTests/com/r_bg/sax_signature/EnvelopingSignatureTest.java (+166 lines)
Added Link Here
1
/*
2
 * Created on Dec 30, 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 com.r_bg.sax_signature;
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.IOException;
14
import java.security.KeyPair;
15
import java.security.KeyPairGenerator;
16
import java.security.NoSuchAlgorithmException;
17
import java.util.zip.GZIPInputStream;
18
19
import javax.xml.parsers.DocumentBuilder;
20
import javax.xml.parsers.FactoryConfigurationError;
21
import javax.xml.parsers.ParserConfigurationException;
22
import javax.xml.parsers.SAXParser;
23
import javax.xml.parsers.SAXParserFactory;
24
25
import org.apache.xml.security.Init;
26
import org.apache.xml.security.c14n.CanonicalizationException;
27
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
28
import org.apache.xml.security.exceptions.XMLSecurityException;
29
import org.apache.xml.security.signature.ObjectContainer;
30
import org.apache.xml.security.signature.XMLSignature;
31
import org.apache.xml.security.signature.XMLSignatureException;
32
import org.apache.xml.security.transforms.TransformationException;
33
import org.apache.xml.security.transforms.Transforms;
34
import org.apache.xml.security.utils.Constants;
35
import org.apache.xml.security.utils.XMLUtils;
36
import org.w3c.dom.Element;
37
38
import junit.framework.Test;
39
import junit.framework.TestCase;
40
import junit.framework.TestSuite;
41
42
/**
43
 * @author raul
44
 *
45
 * TODO To change the template for this generated type comment go to
46
 * Window - Preferences - Java - Code Style - Code Templates
47
 */
48
public class EnvelopingSignatureTest extends TestCase {
49
50
    public static Test suite() {
51
        return new TestSuite(EnvelopingSignatureTest.class);
52
    }
53
    private static void createTestA() throws NoSuchAlgorithmException, FactoryConfigurationError, ParserConfigurationException, XMLSecurityException, TransformationException, XMLSignatureException, IOException, CanonicalizationException, InvalidCanonicalizerException {
54
        Init.init();
55
        javax.xml.parsers.DocumentBuilderFactory dbf =
56
            javax.xml.parsers.DocumentBuilderFactory.newInstance();
57
58
         dbf.setNamespaceAware(true);
59
60
         javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
61
        KeyPair kp=KeyPairGenerator.getInstance("RSA").generateKeyPair();
62
63
          org.w3c.dom.Document doc = db.newDocument();
64
          String BaseURI = "#1";
65
          XMLSignature sig = new XMLSignature(doc, BaseURI,
66
                                              XMLSignature.ALGO_ID_SIGNATURE_RSA,
67
                                              Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
68
          sig.addKeyInfo(kp.getPublic());
69
          Element anElement = doc.createElementNS(null, "RootObject");              
70
          Element anElement2 = doc.createElementNS(null, "UnderObject");
71
          //anElement2.setAttribute("id","1");
72
          //anElement.appendChild(anElement2);
73
          ObjectContainer obj=new ObjectContainer(doc);
74
          obj.getElement().appendChild(anElement2);
75
          obj.setId("1");
76
          sig.appendObject(obj);
77
          anElement.appendChild(sig.getElement());
78
          doc.appendChild(anElement);
79
          anElement2.appendChild(doc.createTextNode("A text in a box"));
80
          Element anElement3 =doc.createElementNS(null,"OtherObject");
81
          anElement2.appendChild(anElement3);
82
          anElement3.appendChild(doc.createElementNS(null,"OtherObject2"));
83
          anElement3.appendChild(doc.createElementNS(null,"OtherObject6"));
84
          anElement3.appendChild(doc.createElementNS(null,"OtherObject"));
85
          {
86
             Transforms transforms = new Transforms(doc);
87
88
             transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
89
             sig.addDocument("#1" , transforms, Constants.ALGO_ID_DIGEST_SHA1);
90
          }
91
92
          {
93
             System.out.println("Start signing");
94
             sig.sign(kp.getPrivate());
95
             System.out.println("Finished signing");
96
              System.out.println("verifying in memory:"+sig.checkSignatureValue(kp.getPublic()));
97
          }
98
99
          ByteArrayOutputStream f = new ByteArrayOutputStream();
100
        XMLUtils.outputDOMc14nWithComments(doc, f);
101
          f.close();
102
          System.out.println("Wrote signature to:" + new String(f.toByteArray()));
103
104
          for (int i=0; i<sig.getSignedInfo().getSignedContentLength(); i++) {
105
             System.out.println("--- Signed Content follows ---:"+i);
106
             System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
107
          }
108
          System.out.println("Signed output:");
109
          ByteArrayOutputStream os=new ByteArrayOutputStream();
110
          sig.getSignedInfo().signInOctectStream(os);
111
          System.out.println(new String(os.toByteArray()));
112
    }
113
    public void testExc() throws Exception{
114
        //createTestA();
115
        String envelopingSig="<RootObject><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
116
                "<ds:SignedInfo>\n" + 
117
                "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:CanonicalizationMethod>\n" + 
118
                "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n" + 
119
                "<ds:Reference URI=\"#1\">\n" + 
120
                "<ds:Transforms>\n" + 
121
                "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:Transform>\n" + 
122
                "</ds:Transforms>\n" + 
123
                "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>\n" + 
124
                "<ds:DigestValue>oMQoFufPA7Un6cfz0GaEOJpE4Z8=</ds:DigestValue>\n" + 
125
                "</ds:Reference>\n" + 
126
                "</ds:SignedInfo>\n" + 
127
                "<ds:SignatureValue>\n" + 
128
                "AhyiFQ6hucykYJOJDBV3wbPBe2TAURXXfCUD7BmSAecT+izT9fHFsxRVez3s+6hYSgtaVhmeVgbd\n" + 
129
                "ZEOMPFihBGldi1NV73Z/tpXxqNvY+/NwQmmasQp9gzFHxYF2cqi8m7sAHM03BIC1YoBctxVw/jxV\n" + 
130
                "ClhLJuTSHoKwlzKH24g=\n" + 
131
                "</ds:SignatureValue>\n" + 
132
                "<ds:KeyInfo>\n" + 
133
                "<ds:KeyValue>\n" + 
134
                "<ds:RSAKeyValue>\n" + 
135
                "<ds:Modulus>\n" + 
136
                "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
137
                "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
138
                "VjevEfohDpn/+oxljm0=\n" + 
139
                "</ds:Modulus>\n" + 
140
                "<ds:Exponent>AQAB</ds:Exponent>\n" + 
141
                "</ds:RSAKeyValue>\n" + 
142
                "</ds:KeyValue>\n" + 
143
                "</ds:KeyInfo>\n" + 
144
                "<ds:Object Id=\"1\"><UnderObject>A text in a box<OtherObject><OtherObject2></OtherObject2><OtherObject6></OtherObject6><OtherObject></OtherObject></OtherObject></UnderObject></ds:Object>\n" + 
145
                "</ds:Signature></RootObject>";
146
        SAXParserFactory sf=SAXParserFactory.newInstance();
147
        sf.setNamespaceAware(true);
148
        EnvelopingSignatureControler eC=new EnvelopingSignatureControler();
149
        sf.newSAXParser().parse(new ByteArrayInputStream(envelopingSig.getBytes()),eC.createSaxHandler());
150
        //System.out.println(new String(((ByteArrayOutputStream)eC.refC14n.os).toByteArray()));
151
        assertTrue("Not Fine",eC.verifyReference(0));
152
        assertTrue("Not Fine",eC.verify());
153
    }
154
    public void test122M() throws Exception{
155
    	SAXParserFactory sf=SAXParserFactory.newInstance();
156
        sf.setNamespaceAware(true);
157
        EnvelopingSignatureControler eC=new EnvelopingSignatureControler();
158
        sf.newSAXParser().parse(new GZIPInputStream(new FileInputStream("122M_sig.xml.gz")),eC.createSaxHandler());
159
        //System.out.println(new String(((ByteArrayOutputStream)eC.refC14n.os).toByteArray()));
160
        assertTrue("Not Fine",eC.verifyReference(0));
161
        assertTrue("Not Fine",eC.verify());
162
    }
163
    static {
164
      Init.init();   
165
    }
166
}
(-)src_unitTests/com/r_bg/sax_signature/OneLevelEnvelopedSignatureTest.java (+198 lines)
Added Link Here
1
/*
2
 * Created on Dec 30, 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 com.r_bg.sax_signature;
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.IOException;
14
import java.security.KeyPair;
15
import java.security.KeyPairGenerator;
16
import java.security.NoSuchAlgorithmException;
17
import java.util.zip.GZIPInputStream;
18
19
import javax.xml.parsers.DocumentBuilder;
20
import javax.xml.parsers.FactoryConfigurationError;
21
import javax.xml.parsers.ParserConfigurationException;
22
import javax.xml.parsers.SAXParser;
23
import javax.xml.parsers.SAXParserFactory;
24
25
import org.apache.xml.security.Init;
26
import org.apache.xml.security.c14n.CanonicalizationException;
27
import org.apache.xml.security.c14n.InvalidCanonicalizerException;
28
import org.apache.xml.security.exceptions.XMLSecurityException;
29
import org.apache.xml.security.signature.ObjectContainer;
30
import org.apache.xml.security.signature.XMLSignature;
31
import org.apache.xml.security.signature.XMLSignatureException;
32
import org.apache.xml.security.transforms.TransformationException;
33
import org.apache.xml.security.transforms.Transforms;
34
import org.apache.xml.security.utils.Constants;
35
import org.apache.xml.security.utils.XMLUtils;
36
import org.w3c.dom.Element;
37
38
import junit.framework.Test;
39
import junit.framework.TestCase;
40
import junit.framework.TestSuite;
41
42
/**
43
 * @author raul
44
 *
45
 * TODO To change the template for this generated type comment go to
46
 * Window - Preferences - Java - Code Style - Code Templates
47
 */
48
public class OneLevelEnvelopedSignatureTest extends TestCase {
49
50
    public static Test suite() {
51
        return new TestSuite(OneLevelEnvelopedSignatureTest.class);
52
    }
53
    private static void createTestA(boolean exclusive) throws NoSuchAlgorithmException, FactoryConfigurationError, ParserConfigurationException, XMLSecurityException, TransformationException, XMLSignatureException, IOException, CanonicalizationException, InvalidCanonicalizerException {
54
        Init.init();
55
        javax.xml.parsers.DocumentBuilderFactory dbf =
56
            javax.xml.parsers.DocumentBuilderFactory.newInstance();
57
58
         dbf.setNamespaceAware(true);
59
60
         javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
61
        KeyPair kp=KeyPairGenerator.getInstance("RSA").generateKeyPair();
62
63
          org.w3c.dom.Document doc = db.newDocument();
64
          String BaseURI = "#1";
65
          XMLSignature sig = new XMLSignature(doc, BaseURI,
66
                                              XMLSignature.ALGO_ID_SIGNATURE_RSA,
67
                                              exclusive ? Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS: Transforms.TRANSFORM_C14N_OMIT_COMMENTS);         
68
          sig.addKeyInfo(kp.getPublic());
69
          Element anEnvelope=doc.createElementNS(null, "Envelope");
70
          anEnvelope.setAttributeNS(Constants.NamespaceSpecNS,"xmlns:a","http://b");
71
          Element anElement = doc.createElementNS(null, "RootObject");              
72
          Element anElement2 = doc.createElementNS(null, "UnderObject");
73
          anElement.setAttribute("Id","1");          
74
          anElement.appendChild(sig.getElement());
75
          anElement.appendChild(anElement2);
76
          anEnvelope.appendChild(anElement);
77
          doc.appendChild(anEnvelope);
78
          anElement2.appendChild(doc.createTextNode("A text in a box"));
79
          Element anElement3 =doc.createElementNS(null,"OtherObject");
80
          anElement2.appendChild(anElement3);
81
          anElement3.appendChild(doc.createElementNS(null,"OtherObject2"));
82
          anElement3.appendChild(doc.createElementNS(null,"OtherObject6"));
83
          anElement3.appendChild(doc.createElementNS(null,"OtherObject"));
84
          {
85
             Transforms transforms = new Transforms(doc);
86
             transforms.addTransform(Transforms.TRANSFORM_ENVELOPED_SIGNATURE);
87
             if (exclusive)
88
             	transforms.addTransform(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS);
89
             
90
             sig.addDocument("#1" , transforms, Constants.ALGO_ID_DIGEST_SHA1);
91
          }
92
93
          {
94
             System.out.println("Start signing");
95
             sig.sign(kp.getPrivate());
96
             System.out.println("Finished signing");
97
              System.out.println("verifying in memory:"+sig.checkSignatureValue(kp.getPublic()));
98
          }
99
100
          ByteArrayOutputStream f = new ByteArrayOutputStream();
101
        XMLUtils.outputDOMc14nWithComments(doc, f);
102
          f.close();
103
          System.out.println("Wrote signature to:" + new String(f.toByteArray()));
104
105
          for (int i=0; i<sig.getSignedInfo().getSignedContentLength(); i++) {
106
             System.out.println("--- Signed Content follows ---:"+i);
107
             System.out.println(new String(sig.getSignedInfo().getSignedContentItem(i)));
108
          }
109
          System.out.println("Signed output:");
110
          ByteArrayOutputStream os=new ByteArrayOutputStream();
111
          sig.getSignedInfo().signInOctectStream(os);
112
          System.out.println(new String(os.toByteArray()));
113
    }
114
    public void testExc() throws Exception{
115
        //createTestA(true);
116
        String envelopingSig="<Envelope xmlns:a=\"http://b\"><RootObject Id=\"1\"><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
117
                "<ds:SignedInfo>\n" + 
118
                "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"></ds:CanonicalizationMethod>\n" + 
119
                "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n" + 
120
                "<ds:Reference URI=\"#1\">\n" + 
121
                "<ds:Transforms>\n" + 
122
                "<ds:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"></ds:Transform>\n" + 
123
                "</ds:Transforms>\n" + 
124
                "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>\n" + 
125
                "<ds:DigestValue>t2hiaMVZW+Z3P2992iEyrDgVLS0=</ds:DigestValue>\n" + 
126
                "</ds:Reference>\n" + 
127
                "</ds:SignedInfo>\n" + 
128
                "<ds:SignatureValue>\n" + 
129
                "ik/EUbz8OgQztvbnK9tbZdf5XSKYc7eMyJ98trW3LoUrxXD47P3gLMnMK5t0JCe+wbxBby0Aux2M\n" + 
130
                "fctuwBsMQve6KwbdvD/2YiS70XmTEvBChCiBYdN1nHfJYyW66xnALoE5V5NuiLrt0cgEggfMTrEy\n" + 
131
                "HYm9g6RQ0IEe/lQCIK4=\n" + 
132
                "</ds:SignatureValue>\n" + 
133
                "<ds:KeyInfo>\n" + 
134
                "<ds:KeyValue>\n" + 
135
                "<ds:RSAKeyValue>\n" + 
136
                "<ds:Modulus>\n" + 
137
                "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
138
                "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
139
                "VjevEfohDpn/+oxljm0=\n" + 
140
                "</ds:Modulus>\n" + 
141
                "<ds:Exponent>AQAB</ds:Exponent>\n" + 
142
                "</ds:RSAKeyValue>\n" + 
143
                "</ds:KeyValue>\n" + 
144
                "</ds:KeyInfo>\n" + 
145
                "</ds:Signature><UnderObject>A text in a box<OtherObject><OtherObject2></OtherObject2><OtherObject6></OtherObject6><OtherObject></OtherObject></OtherObject></UnderObject></RootObject></Envelope>\n" + 
146
                "";
147
        SAXParserFactory sf=SAXParserFactory.newInstance();
148
        sf.setNamespaceAware(true);
149
        OneLevelEnvelopedSignatureControler eC=new OneLevelEnvelopedSignatureControler();
150
        sf.newSAXParser().parse(new ByteArrayInputStream(envelopingSig.getBytes()),eC.createSaxHandler());
151
        //System.out.println(new String(((ByteArrayOutputStream)eC.refC14n.os).toByteArray()));
152
        assertTrue("Not Fine",eC.verifyReference(0));
153
        assertTrue("Not Fine",eC.verify());
154
    }
155
    public void testInc() throws Exception{
156
        createTestA(false);
157
        String envelopingSig="<Envelope xmlns:a=\"http://b\"><RootObject Id=\"1\"><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
158
                "<ds:SignedInfo>\n" + 
159
                "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/TR/2001/REC-xml-c14n-20010315\"></ds:CanonicalizationMethod>\n" + 
160
                "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n" + 
161
                "<ds:Reference URI=\"#1\">\n" + 
162
                "<ds:Transforms>\n" + 
163
                "<ds:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\"></ds:Transform>\n" + 
164
                "</ds:Transforms>\n" + 
165
                "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>\n" + 
166
                "<ds:DigestValue>t2hiaMVZW+Z3P2992iEyrDgVLS0=</ds:DigestValue>\n" + 
167
                "</ds:Reference>\n" + 
168
                "</ds:SignedInfo>\n" + 
169
                "<ds:SignatureValue>\n" + 
170
                "ik/EUbz8OgQztvbnK9tbZdf5XSKYc7eMyJ98trW3LoUrxXD47P3gLMnMK5t0JCe+wbxBby0Aux2M\n" + 
171
                "fctuwBsMQve6KwbdvD/2YiS70XmTEvBChCiBYdN1nHfJYyW66xnALoE5V5NuiLrt0cgEggfMTrEy\n" + 
172
                "HYm9g6RQ0IEe/lQCIK4=\n" + 
173
                "</ds:SignatureValue>\n" + 
174
                "<ds:KeyInfo>\n" + 
175
                "<ds:KeyValue>\n" + 
176
                "<ds:RSAKeyValue>\n" + 
177
                "<ds:Modulus>\n" + 
178
                "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
179
                "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
180
                "VjevEfohDpn/+oxljm0=\n" + 
181
                "</ds:Modulus>\n" + 
182
                "<ds:Exponent>AQAB</ds:Exponent>\n" + 
183
                "</ds:RSAKeyValue>\n" + 
184
                "</ds:KeyValue>\n" + 
185
                "</ds:KeyInfo>\n" + 
186
                "</ds:Signature><UnderObject>A text in a box<OtherObject><OtherObject2></OtherObject2><OtherObject6></OtherObject6><OtherObject></OtherObject></OtherObject></UnderObject></RootObject></Envelope>\n";
187
        SAXParserFactory sf=SAXParserFactory.newInstance();
188
        sf.setNamespaceAware(true);
189
        OneLevelEnvelopedSignatureControler eC=new OneLevelEnvelopedSignatureControler();
190
        sf.newSAXParser().parse(new ByteArrayInputStream(envelopingSig.getBytes()),eC.createSaxHandler());
191
        System.out.println(new String(((ByteArrayOutputStream)eC.refC14n.os).toByteArray()));
192
        assertTrue("Not Fine",eC.verifyReference(0));
193
        assertTrue("Not Fine",eC.verify());
194
    }
195
    static {
196
      Init.init();   
197
    }
198
}
(-)src_unitTests/com/r_bg/sax_signature/SaxHandlerTest.java (+28 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature;
8
9
import junit.framework.Test;
10
import junit.framework.TestCase;
11
import junit.framework.TestSuite;
12
13
/**
14
 * @author raul
15
 *
16
 * TODO To change the template for this generated type comment go to
17
 * Window - Preferences - Java - Code Style - Code Templates
18
 */
19
public class SaxHandlerTest extends TestCase {
20
    public static Test suite() {
21
        return new TestSuite(SaxHandler.class);
22
    }
23
    public void testAddAndRemoveWorkers() {
24
        SignatureControler sc=new SignatureControler();
25
        
26
        //todo
27
    }
28
}
(-)src_unitTests/com/r_bg/sax_signature/SignatureControlerTest.java (+39 lines)
Added Link Here
1
/*
2
 * Created on Dec 18, 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 com.r_bg.sax_signature;
8
9
import junit.framework.Test;
10
import junit.framework.TestCase;
11
import junit.framework.TestSuite;
12
13
/**
14
 * @author raul
15
 *
16
 * TODO To change the template for this generated type comment go to
17
 * Window - Preferences - Java - Code Style - Code Templates
18
 */
19
public class SignatureControlerTest extends TestCase {
20
	public static Test suite() {
21
		return new TestSuite(SignatureControlerTest.class);
22
    }
23
	public void testAddASignature() throws Exception {
24
       
25
        SignatureControler sc=new SignatureControler();
26
        SaxHandler sh=sc.createSaxHandler();
27
        //first nothing expecial
28
        sc.startElement("aaa","eee","aaa:eee",null);
29
        assertEquals("add() called when some garbage",0,sh.workers.size());        
30
        sc.startElement("http://www.w3.org/2000/09/xmldsig#","Signature","ds:Signature",null);
31
        assertEquals("add() not called when a signature",1,sh.workers.size());
32
        sc.endElement("aaa","eee");
33
        assertEquals("remove() called when some garbage",1,sh.workers.size());
34
        sc.endElement("http://www.w3.org/2000/09/xmldsig#","Signature");
35
        assertEquals("remove() not called when a signature",0,sh.workers.size());
36
        
37
	}
38
39
}

Return to bug 32657