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

(-)src/com/r_bg/stax/c14n/C14nInclusive.java (+48 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.util.Iterator;
4
import java.util.SortedSet;
5
import java.util.TreeSet;
6
7
import javax.xml.stream.XMLStreamReader;
8
/**
9
 * TODO: Copy the already defined namespaces sadly stax doesnot give any way to obtain this
10
 * so we are going to have stack for inclusive.
11
 * @author raul
12
 *
13
 */
14
public class C14nInclusive implements C14nAttributeHandler {
15
	public String handleAttributes(XMLStreamReader in,StaxC14nHelper nsD) {
16
		SortedSet args=new TreeSet(new AttributeCompartor(in));
17
		SortedSet nss=new TreeSet(new NsCompartor(in));
18
		String result="";
19
		int length=in.getNamespaceCount();
20
		for (int i=0;i<length;i++) {
21
			if (!nsD.hasBeenRender(in.getNamespacePrefix(i),in.getNamespaceURI(i)))
22
				nss.add(new Integer(i));
23
		}
24
		Iterator it=nss.iterator();
25
		while (it.hasNext()) {
26
			int arg=((Integer)it.next()).intValue();
27
			String prefix=in.getNamespacePrefix(arg);
28
			if (prefix!="") {
29
				prefix=" xmlns:"+prefix;
30
			} else {
31
				prefix=" xmlns";
32
			}
33
			result+=prefix+"=\""+in.getNamespaceURI(arg)+"\"";
34
		}
35
		length=in.getAttributeCount();
36
		for (int i=0;i<length;i++) {
37
			args.add(new Integer(i));			
38
		}
39
		it=args.iterator();
40
		for (int i=0;i<length;i++) {
41
			int arg=((Integer)it.next()).intValue();
42
			result+=" "+C14n.writeAttribute(in,arg)+"=\""+in.getAttributeValue(arg)+"\"";			
43
		}
44
		
45
		return result;
46
	}	
47
48
}
(-)src/com/r_bg/stax/c14n/StaxC14nHelper.java (+55 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
/*
3
 * Copyright  1999-2004 The Apache Software Foundation.
4
 *
5
 *  Licensed under the Apache License, Version 2.0 (the "License");
6
 *  you may not use this file except in compliance with the License.
7
 *  You may obtain a copy of the License at
8
 *
9
 *      http://www.apache.org/licenses/LICENSE-2.0
10
 *
11
 *  Unless required by applicable law or agreed to in writing, software
12
 *  distributed under the License is distributed on an "AS IS" BASIS,
13
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
 *  See the License for the specific language governing permissions and
15
 *  limitations under the License.
16
 *
17
 */
18
19
20
import java.util.ArrayList;
21
import java.util.HashMap;
22
import java.util.List;
23
24
25
26
27
/**
28
 * A stack based Symble Table.
29
 *<br>For speed reasons all the symbols are introduced in the same map,
30
 * and at the same time in a list so it can be removed when the frame is pop back.
31
 * @author Raul Benito
32
 **/
33
public class StaxC14nHelper {
34
	List levels=new ArrayList();
35
	//boolean needToClone=false;
36
	HashMap currentRender=new HashMap();
37
	public StaxC14nHelper() {
38
		currentRender.put("","");
39
	}
40
	public void push() {
41
		levels.add(currentRender.clone());
42
	}
43
	public void pop() {
44
		currentRender=(HashMap) levels.remove(levels.size()-1);
45
	}
46
	public boolean hasBeenRender(String prefix, String uri) {
47
		String previousRendered=(String) currentRender.get(prefix);
48
		if ((previousRendered!=null) && (previousRendered.equals(uri))) {								
49
				return true;			
50
		}
51
		currentRender.put(prefix,uri);
52
		return false;
53
	}
54
	
55
}
(-)src/com/r_bg/stax/c14n/C14n.java (+130 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import javax.xml.namespace.QName;
4
import javax.xml.stream.EventFilter;
5
import javax.xml.stream.StreamFilter;
6
import javax.xml.stream.XMLStreamConstants;
7
import javax.xml.stream.XMLStreamException;
8
import javax.xml.stream.XMLStreamReader;
9
import javax.xml.stream.events.XMLEvent;
10
11
12
public class C14n implements EventFilter,StreamFilter {
13
	String result="";
14
	public static String writePiData(XMLStreamReader in) {
15
		String result=in.getPITarget();
16
		String data=in.getPIData();
17
		if (data!=null && data.length()!=0)
18
			result+=" "+data;
19
		
20
		return result;
21
	}
22
	public static String obtainName(QName name) {		
23
		String prefix=name.getPrefix();
24
		if (prefix!=null && prefix.length()!=0)
25
			prefix+=":";
26
		return prefix+name.getLocalPart();
27
		
28
	}
29
	static String writeAttribute(XMLStreamReader in, int i) {
30
		String result=in.getAttributePrefix(i);
31
		if (result==null) {
32
			result="";
33
		} else {
34
			result+=":";
35
		}
36
		result+=in.getAttributeLocalName(i);
37
		return result;
38
	}
39
	public static String cannoicalizeWithoutComments(XMLStreamReader in, C14nAttributeHandler handler) throws XMLStreamException {		
40
		String result="";
41
		int type;
42
		int beforeDocumentElement=1;
43
		StaxC14nHelper nsD=new StaxC14nHelper();
44
		int number=0;
45
		while ((type=in.getEventType())!=XMLStreamConstants.END_DOCUMENT) {
46
			switch (type) {
47
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
48
				if (beforeDocumentElement==-1)
49
					result+="\n";
50
				result+="<?"+writePiData(in)+"?>";
51
				if (beforeDocumentElement==1)
52
					result+="\n";
53
				break;
54
			case XMLStreamConstants.START_ELEMENT:
55
				number++;
56
				nsD.push();
57
				beforeDocumentElement=0;
58
				result+="<"+obtainName(in.getName());
59
				result+=handler.handleAttributes(in,nsD)+">";
60
				break;
61
			case XMLStreamConstants.END_ELEMENT:
62
				if (--number==0) {
63
					beforeDocumentElement=-1;
64
				}
65
				result+="</"+obtainName(in.getName())+">";
66
				nsD.pop();
67
				break;
68
69
			case XMLStreamConstants.CHARACTERS:
70
			case XMLStreamConstants.CDATA:
71
				result+=in.getText();
72
				break;
73
			
74
						}
75
			in.next();
76
		}
77
		return result;
78
	}
79
80
	int beforeDocumentElement=-1;
81
	int number=0;
82
	C14nAttributeHandler handler;
83
	StaxC14nHelper nsD=new StaxC14nHelper();
84
	public C14n(C14nAttributeHandler handler) {
85
		this.handler=handler;
86
	}
87
	public boolean accept(XMLEvent arg0) {
88
		return false;
89
	}
90
	public boolean accept(XMLStreamReader in) {		
91
		int type=in.getEventType();
92
		switch (type) {
93
			case XMLStreamConstants.PROCESSING_INSTRUCTION:
94
				if (beforeDocumentElement==-1)
95
					result+="\n";
96
				result+="<?"+writePiData(in)+"?>";
97
				if (beforeDocumentElement==1)
98
					result+="\n";
99
				break;
100
			case XMLStreamConstants.START_ELEMENT:
101
				number++;
102
				nsD.push();
103
				beforeDocumentElement=0;
104
				result+="<"+obtainName(in.getName());
105
				result+=handler.handleAttributes(in,nsD)+">";
106
				break;
107
			case XMLStreamConstants.END_ELEMENT:
108
				if (--number==0) {
109
					beforeDocumentElement=-1;
110
				}
111
				result+="</"+obtainName(in.getName())+">";
112
				nsD.pop();
113
				break;
114
115
			case XMLStreamConstants.CHARACTERS:
116
			case XMLStreamConstants.CDATA:
117
				result+=in.getText();
118
				break;
119
			
120
		}
121
		return true;
122
	}
123
	public String getResult() {
124
		return result;
125
	}
126
}
127
	
128
129
130
(-)src/com/r_bg/stax/c14n/C14nAttributeHandler.java (+7 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import javax.xml.stream.XMLStreamReader;
4
5
public interface C14nAttributeHandler {
6
	public String handleAttributes(XMLStreamReader in,StaxC14nHelper nsD);
7
}
(-)src/com/r_bg/stax/c14n/NsComparator.java (+19 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.util.Comparator;
4
5
import javax.xml.stream.XMLStreamReader;
6
7
class NsCompartor implements Comparator {
8
	XMLStreamReader in;
9
	public NsCompartor(XMLStreamReader in) {
10
		this.in=in;
11
	}
12
	public int compare(Object arg0, Object arg1) {
13
		int first=((Integer)arg0).intValue();
14
		int second=((Integer)arg1).intValue();
15
		String uri1=in.getNamespacePrefix(first);
16
		String uri2=in.getNamespacePrefix(second);
17
		return uri1.compareTo(uri2);						
18
	}	
19
}
(-)src/com/r_bg/stax/c14n/AttributeHandleExclusive.java (+58 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.util.HashSet;
4
import java.util.Iterator;
5
import java.util.Set;
6
import java.util.SortedSet;
7
import java.util.TreeSet;
8
9
import javax.xml.namespace.NamespaceContext;
10
import javax.xml.stream.XMLStreamReader;
11
12
public class AttributeHandleExclusive implements C14nAttributeHandler {
13
	public String handleAttributes(XMLStreamReader in,StaxC14nHelper nsD) {
14
		SortedSet args=new TreeSet(new AttributeCompartor(in));
15
		SortedSet nss=new TreeSet();
16
		Set prefixes=new HashSet();
17
		String result="";
18
		int length;
19
		length=in.getAttributeCount();
20
		for (int i=0;i<length;i++) {
21
			args.add(new Integer(i));
22
			String prefix=in.getAttributePrefix(i);
23
			if (prefix!=null)
24
				prefixes.add(prefix);
25
		}		
26
		prefixes.add(in.getPrefix()==null? "" : in.getPrefix());
27
		Iterator it=prefixes.iterator();
28
		NamespaceContext nc=in.getNamespaceContext();
29
		while (it.hasNext()) {
30
			String prefix=(String)it.next();
31
			if (!nsD.hasBeenRender(prefix,nc.getNamespaceURI(prefix)))
32
				nss.add(prefix);
33
		}
34
		it=nss.iterator();
35
		while (it.hasNext()) {			
36
			String realPrefix=(String) it.next();
37
			String prefix=realPrefix;
38
			if (prefix!="") {
39
				prefix=" xmlns:"+prefix;
40
			} else {
41
				prefix=" xmlns";
42
			}
43
			result+=prefix+"=\""+nc.getNamespaceURI(realPrefix)+"\"";
44
		}
45
		
46
		it=args.iterator();
47
		for (int i=0;i<length;i++) {
48
			int arg=((Integer)it.next()).intValue();
49
			result+=" "+C14n.writeAttribute(in,arg)+"=\""+in.getAttributeValue(arg)+"\"";			
50
		}
51
			
52
		return result;
53
	}	
54
55
	}
56
57
58
(-)src/com/r_bg/stax/c14n/AttributeComparator.java (+27 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.util.Comparator;
4
5
import javax.xml.stream.XMLStreamReader;
6
7
class AttributeCompartor implements Comparator {
8
	XMLStreamReader in;
9
	public AttributeCompartor(XMLStreamReader in) {
10
		this.in=in;
11
	}
12
	public int compare(Object arg0, Object arg1) {
13
		int first=((Integer)arg0).intValue();
14
		int second=((Integer)arg1).intValue();
15
		String uri1=in.getAttributeNamespace(first);
16
		String uri2=in.getAttributeNamespace(second);
17
		if (uri1==null) {			
18
			return (uri2!=null )? 1 : 
19
						in.getAttributeLocalName(first).compareTo(in.getAttributeLocalName(second));
20
		}
21
		if (uri2==null) {
22
			return -1;
23
		}			
24
		int result=uri1.compareTo(uri2);		
25
		return  (result!=0) ? result :in.getAttributeLocalName(first).compareTo(in.getAttributeLocalName(second));				
26
	}	
27
}
(-)src/com/r_bg/stax/StaxProvider.java (+66 lines)
Line 0 Link Here
1
/*
2
 * Copyright 2005 The Apache Software Foundation.
3
 *
4
 *  Licensed under the Apache License, Version 2.0 (the "License");
5
 *  you may not use this file except in compliance with the License.
6
 *  You may obtain a copy of the License at
7
 *
8
 *      http://www.apache.org/licenses/LICENSE-2.0
9
 *
10
 *  Unless required by applicable law or agreed to in writing, software
11
 *  distributed under the License is distributed on an "AS IS" BASIS,
12
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
 *  See the License for the specific language governing permissions and
14
 *  limitations under the License.
15
 *
16
 */
17
/*
18
 * ===========================================================================
19
 *
20
 * (C) Copyright IBM Corp. 2003 All Rights Reserved.
21
 *
22
 * ===========================================================================
23
 */
24
/*
25
 * Portions copyright 2005 Sun Microsystems, Inc. All rights reserved.
26
 */
27
/*
28
 * $Id: XMLDSigRI.java 375655 2006-02-07 18:35:54Z mullan $
29
 */
30
package com.r_bg.stax;
31
32
import java.util.*;
33
import java.security.*;
34
35
/**
36
 * The XMLDSig RI Provider.
37
 *
38
 * @author Joyce Leung
39
 */
40
41
/**
42
 * Defines the XMLDSigRI provider.
43
 */
44
45
public final class StaxProvider extends Provider {
46
47
    //static final long serialVersionUID = -5049765099299494554L;
48
49
    private static final String INFO = "XMLDSig " + 
50
    "(Stax XMLSignatureFactory; Stax KeyInfoFactory)";
51
52
    public StaxProvider() {
53
	/* We are the XMLDSig provider */
54
	super("XMLDSig", 1.0, INFO);
55
	
56
	final Map map = new HashMap();
57
        map.put("XMLSignatureFactory.Stax", 
58
	        "com.r_bg.stax.StaxXMLSignatureFactory");
59
        	AccessController.doPrivileged(new java.security.PrivilegedAction() {
60
	    public Object run() {
61
		putAll(map);
62
		return null;
63
	    }
64
	});
65
    }
66
}
(-)src/com/r_bg/stax/IdWatcher.java (+21 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import javax.xml.stream.XMLStreamReader;
4
5
public class IdWatcher implements StaxWatcher {
6
	String uri;
7
	DigestResultListener re;
8
	String algorithm;
9
	public IdWatcher(String uri, String algorithm, DigestResultListener reader) {
10
		this.uri=uri;
11
		this.algorithm=algorithm;
12
		this.re=reader;
13
	}
14
	public StaxWorker watch(XMLStreamReader reader, StaxSignatureVerifer sig) {
15
		if (uri.equals(reader.getAttributeValue(null, "Id"))) {
16
			return new C14nWorker(re,algorithm);
17
		}
18
		return null;
19
	}
20
	
21
}
(-)src/com/r_bg/stax/StaxWorker.java (+8 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import javax.xml.stream.XMLStreamReader;
4
5
public interface StaxWorker {
6
	public StaxWorker read(XMLStreamReader reader);
7
	public StaxWatcher remove(StaxSignatureVerifer verifier);
8
}
(-)src/com/r_bg/stax/StaxWatcher.java (+13 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import javax.xml.stream.XMLStreamReader;
4
5
public interface StaxWatcher {
6
	/**
7
	 * Insert a C14n if needed
8
	 * @param reader
9
	 * @return a StreamFilter to be notified for the life of the element and all
10
	 * subelements.
11
	 */
12
	public StaxWorker watch(XMLStreamReader reader, StaxSignatureVerifer sig);
13
}
(-)src/com/r_bg/stax/StaxValidateContext.java (+137 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import javax.xml.crypto.KeySelector;
4
import javax.xml.crypto.URIDereferencer;
5
import javax.xml.crypto.dsig.XMLSignature;
6
import javax.xml.crypto.dsig.XMLValidateContext;
7
import javax.xml.stream.StreamFilter;
8
import javax.xml.stream.XMLStreamReader;
9
10
public class StaxValidateContext implements XMLValidateContext {	
11
	XMLStreamReader reader;
12
	int signatureNumber=0;
13
	KeySelector ks=null;
14
	private StaxSignatureVerifer sig;
15
	public static StaxValidateContext createEnvelopedValidator(XMLStreamReader reader) {		
16
		return new StaxValidateContext(reader);
17
	}
18
	public void setSignatureNumber(int number) {
19
		signatureNumber=number;
20
	}
21
	
22
	protected StaxValidateContext(XMLStreamReader reader) {
23
		this.reader=reader;		
24
	}
25
	
26
	public String getBaseURI() {
27
		// TODO Auto-generated method stub
28
		return null;
29
	}
30
31
	public void setBaseURI(String baseURI) {
32
		// TODO Auto-generated method stub
33
34
	}
35
36
	public KeySelector getKeySelector() {		
37
		return ks;
38
	}
39
40
	public void setKeySelector(KeySelector ks) {
41
		this.ks=ks;
42
	}
43
44
	public URIDereferencer getURIDereferencer() {
45
		// TODO Auto-generated method stub
46
		return null;
47
	}
48
49
	public void setURIDereferencer(URIDereferencer dereferencer) {
50
		// TODO Auto-generated method stub
51
52
	}
53
54
	public String getNamespacePrefix(String namespaceURI, String defaultPrefix) {
55
		// TODO Auto-generated method stub
56
		return null;
57
	}
58
59
	public String putNamespacePrefix(String namespaceURI, String prefix) {
60
		// TODO Auto-generated method stub
61
		return null;
62
	}
63
64
	public String getDefaultNamespacePrefix() {
65
		// TODO Auto-generated method stub
66
		return null;
67
	}
68
69
	public void setDefaultNamespacePrefix(String defaultPrefix) {
70
		// TODO Auto-generated method stub
71
72
	}
73
74
	public Object setProperty(String name, Object value) {
75
		// TODO Auto-generated method stub
76
		return null;
77
	}
78
79
	public Object getProperty(String name) {
80
		// TODO Auto-generated method stub
81
		return null;
82
	}
83
84
	public Object get(Object key) {
85
		// TODO Auto-generated method stub
86
		return null;
87
	}
88
89
	public Object put(Object key, Object value) {
90
		// TODO Auto-generated method stub
91
		return null;
92
	}
93
94
	public StreamFilter getStreamReader() {
95
		sig = new StaxSignatureVerifer();
96
		// TODO Auto-generated method stub
97
		return sig;
98
	}
99
100
	protected XMLSignature getSignature() {
101
		// TODO Auto-generated method stub
102
		return sig.signatures.get(signatureNumber);
103
	}
104
	/**
105
	 * Obtains a context to validate enveloping signatures or any signature that appears after/inside one
106
	 * of it's reference object.
107
	 * @param reader2
108
	 * @return
109
	 */
110
	public static StaxValidateContext createEnvelopingReader(XMLStreamReader reader2) {
111
		// TODO Auto-generated method stub
112
		return null;
113
	}
114
	/**
115
	 * Marks the current node as a reference target
116
	 * i.e. when reading <element> you must tell the library to begin digesting.
117
	 * <code>
118
	 * <element id="a">
119
	 * </element>
120
	 * 
121
	 * <ds:Signature>
122
	 *   ..
123
	 *   <ds:Refernece URI="#a"
124
	 *   </ds:Reference>
125
	 * </ds:Signature>
126
	 * </code>
127
	 * @param reader2 
128
	 *
129
	 */
130
	public void currentNodeIsReferenceTarget(String id,String canonicalizationMethod, String digestMethod) {
131
		DetachReferenceWorker d=new DetachReferenceWorker(sig,id,canonicalizationMethod,digestMethod);
132
		d.read(reader);
133
		sig.addWorker(d);
134
		
135
	}
136
137
}
(-)src/com/r_bg/stax/C14nWorker.java (+40 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.security.MessageDigest;
4
import java.security.NoSuchAlgorithmException;
5
6
import javax.xml.stream.XMLStreamReader;
7
8
import org.apache.xml.security.algorithms.JCEMapper;
9
import com.r_bg.stax.c14n.C14n;
10
11
public class C14nWorker implements StaxWorker {
12
	DigestResultListener re;
13
	String algorithm;
14
	C14n c14n=new C14n(new com.r_bg.stax.c14n.AttributeHandleExclusive());
15
	public C14nWorker(DigestResultListener re,String algorithm) {
16
		this.re=re;
17
		this.algorithm=algorithm;
18
	}
19
20
	public StaxWorker read(XMLStreamReader reader) {
21
		c14n.accept(reader);
22
		return null;
23
	}
24
25
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
26
		try {
27
			MessageDigest ms=MessageDigest.getInstance(
28
					JCEMapper.translateURItoJCEID(algorithm));
29
			byte [] result=ms.digest(c14n.getResult().getBytes());	
30
			re.setResult(result);
31
			//System.out.println(Base64.encode(result));			
32
		} catch (NoSuchAlgorithmException e) {
33
			// TODO Auto-generated catch block
34
			e.printStackTrace();
35
		}
36
		return null;
37
38
	}
39
40
}
(-)src/com/r_bg/stax/XMLSignatureWorker.java (+138 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.io.IOException;
4
import java.security.InvalidKeyException;
5
import java.security.NoSuchAlgorithmException;
6
import java.security.PublicKey;
7
import java.security.Signature;
8
import java.security.SignatureException;
9
import java.util.List;
10
11
import javax.xml.crypto.KeySelector;
12
import javax.xml.crypto.KeySelectorException;
13
import javax.xml.crypto.KeySelectorResult;
14
import javax.xml.crypto.MarshalException;
15
import javax.xml.crypto.dsig.Reference;
16
import javax.xml.crypto.dsig.SignedInfo;
17
import javax.xml.crypto.dsig.XMLSignContext;
18
import javax.xml.crypto.dsig.XMLSignature;
19
import javax.xml.crypto.dsig.XMLSignatureException;
20
import javax.xml.crypto.dsig.XMLValidateContext;
21
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
22
import javax.xml.stream.XMLStreamConstants;
23
import javax.xml.stream.XMLStreamReader;
24
25
import org.apache.xml.security.algorithms.JCEMapper;
26
class Constants {
27
	public static final String DS_URI="http://www.w3.org/2000/09/xmldsig#";
28
}
29
30
31
32
class SignatureWatcher implements StaxWatcher {	
33
	public StaxWorker watch(XMLStreamReader reader, StaxSignatureVerifer sig) {
34
		String name=reader.getLocalName();
35
		String uri=reader.getNamespaceURI();
36
		if (name.equals("Signature") && 
37
				uri.equals(Constants.DS_URI)) {
38
			System.out.println("Signature!!!!!!");
39
			XMLSignatureWorker s=new XMLSignatureWorker();
40
			sig.addSignature(s);
41
			return s;
42
		}
43
		return null;
44
	}
45
46
}
47
48
public class XMLSignatureWorker implements StaxWorker,XMLSignature {		
49
	SignedInfoWorker si;
50
	KeySelectorResult keySelectorResult=null;
51
	SignedValueWorker signatureValue;
52
	public StaxWorker read(XMLStreamReader reader) {
53
		if  ( (reader.getEventType()==XMLStreamConstants.START_ELEMENT) &&
54
				Constants.DS_URI.equals(reader.getNamespaceURI() ) ) {
55
			if (reader.getLocalName().equals("SignedInfo") )  {
56
				si=new SignedInfoWorker();
57
				return si;			
58
			}
59
			if (reader.getLocalName().equals("SignatureValue") )  {
60
				signatureValue=new SignedValueWorker();
61
				return signatureValue; 			
62
			}
63
		}
64
		return null;
65
	}
66
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
67
		System.out.println("Signature finished!");
68
		return null;
69
	}
70
	public boolean validate(XMLValidateContext validateContext) throws XMLSignatureException {		
71
		List<Reference> references=si.getReferences();
72
		boolean valid=true;
73
		for (Reference ref :  references){
74
			valid&=ref.validate(validateContext);
75
		} 
76
		try {
77
			KeySelector ks=validateContext.getKeySelector();
78
			keySelectorResult=ks.select(null, KeySelector.Purpose.VERIFY, 
79
					si.getSignatureMethod(), validateContext);			
80
		} catch (KeySelectorException e) {
81
			// TODO Auto-generated catch block
82
			e.printStackTrace();
83
		}
84
		try {
85
		Signature sig=Signature.getInstance(
86
				JCEMapper.translateURItoJCEID(si.getSignatureMethod().getAlgorithm()));
87
			sig.initVerify((PublicKey) keySelectorResult.getKey());
88
			int available=si.getCanonicalizedData().available();
89
			byte [] input=new byte[available];
90
			si.getCanonicalizedData().read(input);		
91
			sig.update(input);					
92
			valid&=sig.verify(getSignatureValue().getValue());
93
		} catch (SignatureException e) {
94
			// TODO Auto-generated catch block
95
			e.printStackTrace();
96
		} catch (NoSuchAlgorithmException e) {
97
			// TODO Auto-generated catch block
98
			e.printStackTrace();
99
		} catch (InvalidKeyException e) {
100
			// TODO Auto-generated catch block
101
			e.printStackTrace();
102
		} catch (IOException e) {
103
			// TODO Auto-generated catch block
104
			e.printStackTrace();
105
		}
106
		return valid;
107
	}
108
	public KeyInfo getKeyInfo() {
109
		// TODO Auto-generated method stub
110
		return null;
111
	}
112
	public SignedInfo getSignedInfo() {
113
		return si;
114
	}
115
	public List getObjects() {
116
		// TODO Auto-generated method stub
117
		return null;
118
	}
119
	public String getId() {
120
		// TODO Auto-generated method stub
121
		return null;
122
	}
123
	public SignatureValue getSignatureValue() {	
124
		return signatureValue;
125
	}
126
	public void sign(XMLSignContext signContext) throws MarshalException, XMLSignatureException {
127
		// TODO Auto-generated method stub
128
		
129
	}
130
	public KeySelectorResult getKeySelectorResult() {		
131
		return keySelectorResult;
132
	}
133
	public boolean isFeatureSupported(String feature) {
134
		// TODO Auto-generated method stub
135
		return false;
136
	}
137
	
138
}
(-)src/com/r_bg/stax/DigestResultListener.java (+6 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
interface DigestResultListener {	
4
	public void setResult(byte[] result);
5
6
}
(-)src/com/r_bg/stax/StaxXMLSignatureFactory.java (+174 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.security.InvalidAlgorithmParameterException;
4
import java.security.NoSuchAlgorithmException;
5
import java.security.Security;
6
import java.util.List;
7
8
import javax.xml.crypto.Data;
9
import javax.xml.crypto.MarshalException;
10
import javax.xml.crypto.URIDereferencer;
11
import javax.xml.crypto.XMLStructure;
12
import javax.xml.crypto.dsig.CanonicalizationMethod;
13
import javax.xml.crypto.dsig.DigestMethod;
14
import javax.xml.crypto.dsig.Manifest;
15
import javax.xml.crypto.dsig.Reference;
16
import javax.xml.crypto.dsig.SignatureMethod;
17
import javax.xml.crypto.dsig.SignatureProperties;
18
import javax.xml.crypto.dsig.SignatureProperty;
19
import javax.xml.crypto.dsig.SignedInfo;
20
import javax.xml.crypto.dsig.Transform;
21
import javax.xml.crypto.dsig.XMLObject;
22
import javax.xml.crypto.dsig.XMLSignature;
23
import javax.xml.crypto.dsig.XMLSignatureFactory;
24
import javax.xml.crypto.dsig.XMLValidateContext;
25
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
26
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
27
import javax.xml.crypto.dsig.spec.DigestMethodParameterSpec;
28
import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec;
29
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
30
31
public class StaxXMLSignatureFactory extends XMLSignatureFactory {
32
	static {
33
      
34
                Security.addProvider(new StaxProvider());
35
      
36
    }@Override
37
	public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki) {
38
		// TODO Auto-generated method stub
39
		return null;
40
	}
41
42
	@Override
43
	public XMLSignature newXMLSignature(SignedInfo si, KeyInfo ki, List objects, String id, String signatureValueId) {
44
		// TODO Auto-generated method stub
45
		return null;
46
	}
47
48
	@Override
49
	public Reference newReference(String uri, DigestMethod dm) {
50
		// TODO Auto-generated method stub
51
		return null;
52
	}
53
54
	@Override
55
	public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id) {
56
		// TODO Auto-generated method stub
57
		return null;
58
	}
59
60
	@Override
61
	public Reference newReference(String uri, DigestMethod dm, List transforms, String type, String id, byte[] digestValue) {
62
		// TODO Auto-generated method stub
63
		return null;
64
	}
65
66
	@Override
67
	public Reference newReference(String uri, DigestMethod dm, List appliedTransforms, Data result, List transforms, String type, String id) {
68
		// TODO Auto-generated method stub
69
		return null;
70
	}
71
72
	@Override
73
	public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references) {
74
		// TODO Auto-generated method stub
75
		return null;
76
	}
77
78
	@Override
79
	public SignedInfo newSignedInfo(CanonicalizationMethod cm, SignatureMethod sm, List references, String id) {
80
		// TODO Auto-generated method stub
81
		return null;
82
	}
83
84
	@Override
85
	public XMLObject newXMLObject(List content, String id, String mimeType, String encoding) {
86
		// TODO Auto-generated method stub
87
		return null;
88
	}
89
90
	@Override
91
	public Manifest newManifest(List references) {
92
		// TODO Auto-generated method stub
93
		return null;
94
	}
95
96
	@Override
97
	public Manifest newManifest(List references, String id) {
98
		// TODO Auto-generated method stub
99
		return null;
100
	}
101
102
	@Override
103
	public SignatureProperty newSignatureProperty(List content, String target, String id) {
104
		// TODO Auto-generated method stub
105
		return null;
106
	}
107
108
	@Override
109
	public SignatureProperties newSignatureProperties(List properties, String id) {
110
		// TODO Auto-generated method stub
111
		return null;
112
	}
113
114
	@Override
115
	public DigestMethod newDigestMethod(String algorithm, DigestMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
116
		// TODO Auto-generated method stub
117
		return null;
118
	}
119
120
	@Override
121
	public SignatureMethod newSignatureMethod(String algorithm, SignatureMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
122
		// TODO Auto-generated method stub
123
		return null;
124
	}
125
126
	@Override
127
	public Transform newTransform(String algorithm, TransformParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
128
		// TODO Auto-generated method stub
129
		return null;
130
	}
131
132
	@Override
133
	public Transform newTransform(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
134
		// TODO Auto-generated method stub
135
		return null;
136
	}
137
138
	@Override
139
	public CanonicalizationMethod newCanonicalizationMethod(String algorithm, C14NMethodParameterSpec params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
140
		// TODO Auto-generated method stub
141
		return null;
142
	}
143
144
	@Override
145
	public CanonicalizationMethod newCanonicalizationMethod(String algorithm, XMLStructure params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
146
		// TODO Auto-generated method stub
147
		return null;
148
	}
149
150
	@Override
151
	public XMLSignature unmarshalXMLSignature(XMLValidateContext context) throws MarshalException {
152
		// TODO Auto-generated method stub
153
		return ((StaxValidateContext)context).getSignature();
154
	}
155
156
	@Override
157
	public XMLSignature unmarshalXMLSignature(XMLStructure xmlStructure) throws MarshalException {
158
		// TODO Auto-generated method stub
159
		return null;
160
	}
161
162
	@Override
163
	public boolean isFeatureSupported(String feature) {
164
		// TODO Auto-generated method stub
165
		return false;
166
	}
167
168
	@Override
169
	public URIDereferencer getURIDereferencer() {
170
		// TODO Auto-generated method stub
171
		return null;
172
	}
173
174
}
(-)src/com/r_bg/stax/SignatureMethodWorker.java (+41 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.security.spec.AlgorithmParameterSpec;
4
5
import javax.xml.crypto.dsig.SignatureMethod;
6
import javax.xml.stream.XMLStreamConstants;
7
import javax.xml.stream.XMLStreamReader;
8
9
public class SignatureMethodWorker implements StaxWorker, SignatureMethod {
10
11
	private String sighantureMethod;
12
13
	public StaxWorker read(XMLStreamReader reader) {
14
		if (reader.getEventType()==XMLStreamConstants.START_ELEMENT && Constants.DS_URI.equals(reader.getNamespaceURI())) {
15
			if ("SignatureMethod".equals(reader.getLocalName())) {
16
				sighantureMethod=reader.getAttributeValue(null, "Algorithm");			
17
			};
18
		}
19
		return null;
20
	}
21
22
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
23
		// TODO Auto-generated method stub
24
		return null;
25
	}
26
27
	public AlgorithmParameterSpec getParameterSpec() {
28
		// TODO Auto-generated method stub
29
		return null;
30
	}
31
32
	public boolean isFeatureSupported(String feature) {
33
		// TODO Auto-generated method stub
34
		return false;
35
	}
36
37
	public String getAlgorithm() {
38
		return sighantureMethod;
39
	}
40
41
}
(-)src/com/r_bg/stax/SignedValueWorker.java (+55 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import javax.xml.crypto.dsig.XMLSignatureException;
4
import javax.xml.crypto.dsig.XMLValidateContext;
5
import javax.xml.crypto.dsig.XMLSignature.SignatureValue;
6
import javax.xml.stream.XMLStreamConstants;
7
import javax.xml.stream.XMLStreamReader;
8
9
import org.apache.xml.security.exceptions.Base64DecodingException;
10
import org.apache.xml.security.utils.Base64;
11
12
public class SignedValueWorker implements StaxWorker, SignatureValue {
13
	String data;
14
	public SignedValueWorker() {		
15
	}
16
17
	public StaxWorker read(XMLStreamReader reader) {
18
		if (reader.getEventType()==XMLStreamConstants.CHARACTERS) {
19
			data=reader.getText();
20
		}
21
		return null;
22
	}
23
24
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
25
		//System.out.println("Signature Value:"+data);		
26
		return null;
27
	}
28
29
	public String getId() {
30
		// TODO Auto-generated method stub
31
		return null;
32
	}
33
34
	public byte[] getValue()  {
35
		System.out.println("SignedInfo:"+data);
36
		try {
37
			return Base64.decode(data);
38
		} catch (Base64DecodingException e) {
39
			// TODO Auto-generated catch block
40
			e.printStackTrace();
41
		}
42
		return null;
43
	}
44
45
	public boolean validate(XMLValidateContext validateContext) throws XMLSignatureException {
46
		// TODO Auto-generated method stub
47
		return false;
48
	}
49
50
	public boolean isFeatureSupported(String feature) {
51
		// TODO Auto-generated method stub
52
		return false;
53
	}
54
55
}
(-)src/com/r_bg/stax/SignedInfoWorker.java (+72 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.io.ByteArrayInputStream;
4
import java.io.InputStream;
5
import java.util.ArrayList;
6
import java.util.List;
7
8
import javax.xml.crypto.dsig.CanonicalizationMethod;
9
import javax.xml.crypto.dsig.SignatureMethod;
10
import javax.xml.crypto.dsig.SignedInfo;
11
import javax.xml.stream.XMLStreamConstants;
12
import javax.xml.stream.XMLStreamReader;
13
14
import com.r_bg.stax.c14n.AttributeHandleExclusive;
15
import com.r_bg.stax.c14n.C14n;
16
17
public class SignedInfoWorker implements StaxWorker, SignedInfo {
18
	//	FIXME: Only exclusive C14n
19
	C14n c14n=new C14n(new AttributeHandleExclusive() );
20
	List<ReferenceWorker> references=new ArrayList<ReferenceWorker>();	
21
	private SignatureMethodWorker smw;
22
	public StaxWorker read(XMLStreamReader reader) {
23
		c14n.accept(reader);
24
		if (reader.getEventType()==XMLStreamConstants.START_ELEMENT && Constants.DS_URI.equals(reader.getNamespaceURI())) {
25
			if ("SignatureMethod".equals(reader.getLocalName())) {
26
				 smw=new SignatureMethodWorker();
27
				 return smw;
28
			}
29
			if (reader.getLocalName().equals("Reference") ) {
30
				ReferenceWorker r=new ReferenceWorker();
31
				references.add(r);
32
				return r;			
33
			}
34
		}
35
		return null;
36
	}
37
38
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
39
		//System.out.println("C14n------\n"+c14n.getResult()+"\n\\C14n-------");
40
		return null;
41
	}
42
43
	public CanonicalizationMethod getCanonicalizationMethod() {
44
		// TODO Auto-generated method stub
45
		return null;
46
	}
47
48
	public SignatureMethod getSignatureMethod() {
49
		return smw;
50
	}
51
52
	public List getReferences() {
53
		// TODO Auto-generated method stub
54
		return references;
55
	}
56
57
	public String getId() {
58
		// TODO Auto-generated method stub
59
		return null;
60
	}
61
62
	public InputStream getCanonicalizedData() {
63
		//FIXME: Only exclusive C14n
64
		return new ByteArrayInputStream(c14n.getResult().getBytes());
65
	}
66
67
	public boolean isFeatureSupported(String feature) {
68
		// TODO Auto-generated method stub
69
		return false;
70
	}
71
	
72
}
(-)src/com/r_bg/stax/ReferenceWorker.java (+137 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.io.InputStream;
4
import java.security.spec.AlgorithmParameterSpec;
5
import java.util.Arrays;
6
import java.util.List;
7
8
import javax.xml.crypto.Data;
9
import javax.xml.crypto.dsig.DigestMethod;
10
import javax.xml.crypto.dsig.Reference;
11
import javax.xml.crypto.dsig.XMLSignatureException;
12
import javax.xml.crypto.dsig.XMLValidateContext;
13
import javax.xml.stream.XMLStreamConstants;
14
import javax.xml.stream.XMLStreamReader;
15
16
import org.apache.xml.security.exceptions.Base64DecodingException;
17
import org.apache.xml.security.utils.Base64;
18
19
class ReferenceWorker implements StaxWorker, Reference, DigestResultListener {	
20
	boolean readDigestValue=false;
21
	String uri;
22
	String c14nType;
23
	byte[] digestValue;
24
	byte[] calculateDigestValue;
25
	boolean correct=false;
26
	private DigestMethod digestMethod;
27
	
28
	public StaxWorker read(XMLStreamReader reader) {
29
		if (reader.getEventType()==XMLStreamConstants.START_ELEMENT && Constants.DS_URI.equals(reader.getNamespaceURI())) {
30
			String name=reader.getLocalName();
31
			if (name.equals("Reference") ) {
32
				uri=reader.getAttributeValue(null,"URI");
33
			}
34
			if (name.equals("DigestValue")) {
35
				readDigestValue=true;
36
			}	
37
			if ("DigestMethod".equals(name)) {
38
				final String mda=reader.getAttributeValue(null, "Algorithm");
39
				digestMethod=new DigestMethod() {
40
41
					public AlgorithmParameterSpec getParameterSpec() {
42
						return null;
43
					}
44
45
					public boolean isFeatureSupported(String feature) {
46
						// TODO Auto-generated method stub
47
						return false;
48
					}
49
50
					public String getAlgorithm() {
51
						return mda;
52
					}
53
					
54
				};				
55
			}
56
		}
57
		if (reader.getEventType()==XMLStreamConstants.END_ELEMENT && 
58
				Constants.DS_URI.equals(reader.getNamespaceURI())) {
59
			if (reader.getLocalName().equals("DigestValue")) {
60
				readDigestValue=false;
61
			}
62
		}
63
		if (reader.getEventType()==XMLStreamConstants.CHARACTERS) {
64
			if (readDigestValue)
65
				try {
66
					digestValue=Base64.decode(reader.getText());
67
				} catch (Base64DecodingException e) {
68
					// TODO Auto-generated catch block
69
					e.printStackTrace();
70
				}
71
		}
72
		// TODO Auto-generated method stub
73
		return null;
74
	}
75
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
76
		//System.out.println("Reference removed");
77
		//TODO: Check if there is already a reference runnig.
78
		String uriRef=uri.substring(1);
79
		DetachReferenceWorker refernece=verifier.getReference(uriRef);
80
		if (refernece==null)
81
			return new IdWatcher(uriRef,getDigestMethod().getAlgorithm(),this);
82
		refernece.addListener(this);
83
		return null;
84
	}
85
	/* (non-Javadoc)
86
	 * @see com.r_bg.stax.DigestResultListener#setResult(byte[])
87
	 */
88
	public void setResult(byte[] result) {
89
		calculateDigestValue=result;		
90
		correct=Arrays.equals(result, digestValue);
91
		if (!correct) {
92
			System.out.println("Expected:"+Base64.encode(result)+" Actual:"
93
					+Base64.encode(digestValue));
94
		}
95
		
96
	}
97
	public List getTransforms() {
98
		// TODO Auto-generated method stub
99
		return null;
100
	}
101
	public DigestMethod getDigestMethod() {
102
		return digestMethod;
103
	}
104
	public String getId() {
105
		// TODO Auto-generated method stub
106
		return null;
107
	}
108
	public byte[] getDigestValue() {
109
		return digestValue;
110
	}
111
	public byte[] getCalculatedDigestValue() {
112
		return calculateDigestValue;
113
	}
114
	public boolean validate(XMLValidateContext validateContext) throws XMLSignatureException {
115
		return correct;
116
	}
117
	public Data getDereferencedData() {
118
		// TODO Auto-generated method stub
119
		return null;
120
	}
121
	public InputStream getDigestInputStream() {
122
		// TODO Auto-generated method stub
123
		return null;
124
	}
125
	public String getURI() {
126
		return uri;
127
	}
128
	public String getType() {
129
		// TODO Auto-generated method stub
130
		return null;
131
	}
132
	public boolean isFeatureSupported(String feature) {
133
		// TODO Auto-generated method stub
134
		return false;
135
	}
136
	
137
}
(-)src/com/r_bg/stax/StaxSignatureVerifer.java (+100 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.util.ArrayList;
4
import java.util.HashMap;
5
import java.util.List;
6
import java.util.Map;
7
8
import javax.xml.crypto.dsig.Reference;
9
import javax.xml.crypto.dsig.XMLSignatureException;
10
import javax.xml.stream.StreamFilter;
11
import javax.xml.stream.XMLStreamConstants;
12
import javax.xml.stream.XMLStreamReader;
13
14
15
16
17
public class StaxSignatureVerifer implements StreamFilter{
18
	List<XMLSignatureWorker> signatures=new ArrayList<XMLSignatureWorker>();
19
	List<StaxWorker> filters=new ArrayList<StaxWorker>();
20
	List<Integer> filterStart=new ArrayList<Integer>();
21
	List<StaxWatcher> watchers=new ArrayList<StaxWatcher>();
22
	int level=0;
23
	public StaxSignatureVerifer() {
24
		watchers.add(new SignatureWatcher());
25
	}
26
	public void addSignature(XMLSignatureWorker s) {
27
		signatures.add(s);
28
		
29
	}
30
	public void addWatch(StaxWatcher watcher) {
31
		watchers.add(watcher);		
32
	}
33
	public void addWorker(StaxWorker worker) {
34
		filters.add(worker);
35
		filterStart.add(level);
36
	}
37
	public boolean accept(XMLStreamReader arg0) {
38
		if (arg0.getEventType()==XMLStreamConstants.START_ELEMENT) {
39
			level++;
40
			for (StaxWatcher watcher : watchers) {
41
				StaxWorker sf=watcher.watch(arg0, this);
42
				if (sf!=null) {
43
					filters.add(sf);
44
					filterStart.add(level);
45
				}
46
			}
47
		}
48
		List<StaxWorker> added=filters;
49
		while (added.size()!=0) {			
50
			List<StaxWorker> toAdd=new ArrayList<StaxWorker>();
51
			List<Integer> toAddStart=new ArrayList<Integer>();						
52
			for (StaxWorker filter: added) {
53
				StaxWorker sf=filter.read(arg0);
54
				if (sf!=null) {
55
					toAdd.add(sf);
56
					toAddStart.add(level);
57
				}
58
			}			
59
			added=toAdd;
60
			filters.addAll(toAdd);
61
			filterStart.addAll(toAddStart);
62
		}
63
		if (arg0.getEventType()==XMLStreamConstants.END_ELEMENT) {			
64
			do {
65
				int i=filterStart.lastIndexOf(level);
66
				if (i!=-1) {
67
					StaxWatcher watch=filters.remove(i).remove(this);
68
					if (watch!=null) {
69
						watchers.add(watch);
70
					}
71
					filterStart.remove(i);
72
				}
73
			} while (filterStart.contains(level));
74
			level--;
75
		}
76
		// TODO Auto-generated method stub
77
		return true;
78
	}
79
80
	public boolean getReferenceResult(int i) {
81
		// TODO Auto-generated method stub
82
		try {
83
			return ((Reference)signatures.get(0).getSignedInfo().getReferences().get(0)).validate(null);
84
		} catch (XMLSignatureException e) {
85
			// TODO Auto-generated catch block
86
			e.printStackTrace();
87
		}
88
		return false;
89
	}
90
	Map<String,DetachReferenceWorker> references=new HashMap<String, DetachReferenceWorker>(); 
91
	public void addReference(String id, DetachReferenceWorker worker) {
92
		references.put(id,worker);
93
		
94
	}
95
	public DetachReferenceWorker getReference(String uriRef) {
96
		// TODO Auto-generated method stub
97
		return references.get(uriRef);
98
	}
99
100
}
(-)src/com/r_bg/stax/DetachReferenceWorker.java (+63 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
4
import java.util.ArrayList;
5
import java.util.List;
6
7
import javax.xml.stream.XMLStreamConstants;
8
import javax.xml.stream.XMLStreamReader;
9
10
public class DetachReferenceWorker implements DigestResultListener, StaxWorker{
11
	private String id;
12
	private StaxSignatureVerifer ver;
13
	private C14nWorker worker;
14
	boolean envolopeSignatureTransformation=true;
15
	boolean inSignature=false;
16
	List<DigestResultListener> listeners=new ArrayList<DigestResultListener>();
17
	byte[] result=null;
18
	public DetachReferenceWorker(StaxSignatureVerifer ver,
19
			String id, String c14nmethod, String digestMethod) {
20
		this.id=id;
21
		this.ver=ver;
22
		worker=new C14nWorker(this,digestMethod);
23
		ver.addReference(id,this);
24
	};
25
	public void setResult(byte[] result) {
26
		this.result=result;
27
		for (DigestResultListener listener: listeners) {
28
			listener.setResult(result);
29
		}
30
		
31
	}
32
	public StaxWorker read(XMLStreamReader reader) {
33
		if (envolopeSignatureTransformation) {
34
			if (inSignature)
35
				return null;
36
			if ((reader.getEventType()== XMLStreamReader.START_ELEMENT) && (reader.getLocalName().equals("Signature") && 
37
					reader.getNamespaceURI().equals(Constants.DS_URI)) ) {
38
				inSignature=true;
39
				return this;
40
			}
41
		}		
42
		worker.read(reader);		
43
		return null;
44
	}
45
	public StaxWatcher remove(StaxSignatureVerifer verifier) {
46
		if (inSignature) {
47
			inSignature=false;
48
			return null;
49
		}
50
		worker.remove(verifier);
51
		System.out.println("Raul!!!:"+worker.c14n.getResult());
52
		return null;
53
	}
54
	public void addListener(DigestResultListener listener) {
55
		if (result!=null) {
56
			listener.setResult(result);
57
			return;
58
		}
59
		listeners.add(listener);
60
		
61
	}
62
63
}
(-)src_unitTests/org/apache/xml/security/test/encryption/XMLCipherTester.java (-1 / +1 lines)
Lines 81-87 Link Here
81
    }
81
    }
82
82
83
    protected void setUp() {
83
    protected void setUp() {
84
        String basedir = System.getProperty("basedir");
84
        String basedir = System.getProperty("basedir",".");
85
        documentName = System.getProperty("org.apache.xml.enc.test.doc",
85
        documentName = System.getProperty("org.apache.xml.enc.test.doc",
86
            basedir + "/build.xml");
86
            basedir + "/build.xml");
87
        elementName = System.getProperty("org.apache.xml.enc.test.elem",
87
        elementName = System.getProperty("org.apache.xml.enc.test.elem",
(-)src_unitTests/com/r_bg/stax/c14n/C14nIncl.java (+169 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.io.ByteArrayInputStream;
4
5
import javax.xml.stream.XMLInputFactory;
6
import javax.xml.stream.XMLStreamException;
7
import javax.xml.stream.XMLStreamReader;
8
9
import junit.framework.TestCase;
10
11
public class C14nIncl extends TestCase {
12
13
	public static void main(String[] args) {
14
	}
15
	public static void testRfc3_1() throws Exception {
16
		String in="<?xml version=\"1.0\"?>\n" + 
17
				"\n" + 
18
				"<?xml-stylesheet   href=\"doc.xsl\"\n" + 
19
				"   type=\"text/xsl\"   ?>\n" + 
20
				"\n" + 
21
				"<!DOCTYPE doc SYSTEM \"doc.dtd\">\n" + 
22
				"\n" + 
23
				"<doc>Hello, world!<!-- Comment 1 --></doc>\n" + 
24
				"\n" + 
25
				"<?pi-without-data     ?>\n" + 
26
				"\n" + 
27
				"<!-- Comment 2 -->\n" + 
28
				"\n" + 
29
				"<!-- Comment 3 -->";
30
		String outWithoutComments="<?xml-stylesheet href=\"doc.xsl\"\n" + 
31
				"   type=\"text/xsl\"   ?>\n" + 
32
				"<doc>Hello, world!</doc>\n" + 
33
				"<?pi-without-data?>";
34
		String outWithComments="<?xml-stylesheet href=\"doc.xsl\"\n" + 
35
				"   type=\"text/xsl\"   ?>\n" + 
36
				"<doc>Hello, world!<!-- Comment 1 --></doc>\n" + 
37
				"<?pi-without-data?>\n" + 
38
				"<!-- Comment 2 -->\n" + 
39
				"<!-- Comment 3 -->";
40
		XMLInputFactory im=XMLInputFactory.newInstance();
41
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));
42
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));		
43
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
44
				C14n.cannoicalizeWithoutComments(reader,new C14nInclusive()));
45
		
46
	}
47
	public static void testRfc3_2() throws Exception {
48
		String in="<doc>\n" + 
49
				"   <clean>   </clean>\n" + 
50
				"   <dirty>   A   B   </dirty>\n" + 
51
				"   <mixed>\n" + 
52
				"      A\n" + 
53
				"      <clean>   </clean>\n" + 
54
				"      B\n" + 
55
				"      <dirty>   A   B   </dirty>\n" + 
56
				"      C\n" + 
57
				"   </mixed>\n" + 
58
				"</doc>";
59
		String outWithoutComments="<doc>\n" + 
60
				"   <clean>   </clean>\n" + 
61
				"   <dirty>   A   B   </dirty>\n" + 
62
				"   <mixed>\n" + 
63
				"      A\n" + 
64
				"      <clean>   </clean>\n" + 
65
				"      B\n" + 
66
				"      <dirty>   A   B   </dirty>\n" + 
67
				"      C\n" + 
68
				"   </mixed>\n" + 
69
				"</doc>";
70
		XMLInputFactory im=XMLInputFactory.newInstance();
71
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));
72
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));		
73
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
74
				C14n.cannoicalizeWithoutComments(reader,new C14nInclusive()));
75
		
76
	}
77
	public static void testOrderInAttributes() throws Exception {
78
		String in="<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + 
79
				"<doc xmlns:b=\"http://www.ietf.org\">" + 
80
				"     <doc2 xmlns:a=\"http://www.w3.org\">" + 
81
				"      <doc3 xmlns=\"http://example.org\">\n" + 
82
				"   <e3   name = \"elem3\"   id=\"elem3\"   />\n" + 
83
				"   <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + 
84
				"      />\n" + 								
85
				"</doc3></doc2></doc>";
86
		String outWithoutComments="<doc xmlns:b=\"http://www.ietf.org\">     <doc2 xmlns:a=\"http://www.w3.org\">      <doc3 xmlns=\"http://example.org\">\n" + 
87
				"   <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + 
88
				"   <e5 attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + 
89
				"</doc3></doc2></doc>";
90
		XMLInputFactory im=XMLInputFactory.newInstance();
91
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));
92
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));		
93
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
94
				C14n.cannoicalizeWithoutComments(reader,new C14nInclusive()));		
95
		
96
	}
97
	public static void testOrderBetwenAttributesAndNss() throws Exception {
98
		String in="<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + 
99
				"<doc>\n"+
100
				"   <e3   name = \"elem3\" xmlns=\"http://a.com/\"  id=\"elem3\"   />\n" + 
101
				"</doc>";
102
		String outWithoutComments="<doc>\n"+
103
			"   <e3 xmlns=\"http://a.com/\" id=\"elem3\" name=\"elem3\"></e3>\n" + 
104
			"</doc>";
105
		XMLInputFactory im=XMLInputFactory.newInstance();
106
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));
107
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
108
		
109
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
110
				C14n.cannoicalizeWithoutComments(reader,new C14nInclusive()));
111
		
112
	}
113
	public static void testRfc3_3() throws Exception {
114
		String in="<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + 
115
				"<doc>\n" + 
116
				"   <e1   />\n" + 
117
				"   <e2   ></e2>\n" + 
118
				"   <e3   name = \"elem3\"   id=\"elem3\"   />\n" + 
119
				"   <e4   name=\"elem4\"   id=\"elem4\"   ></e4>\n" + 
120
				"   <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + 
121
				"      xmlns:b=\"http://www.ietf.org\"\n" + 
122
				"      xmlns:a=\"http://www.w3.org\"\n" + 
123
				"      xmlns=\"http://example.org\"/>\n" + 
124
				"   <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + 
125
				"      <e7 xmlns=\"http://www.ietf.org\">\n" + 
126
				"         <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + 
127
				"            <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + 
128
				"         </e8>\n" + 
129
				"      </e7>\n" + 
130
				"   </e6>\n" + 
131
				"</doc>";
132
		String outWithoutComments="<doc>\n" + 
133
				"   <e1></e1>\n" + 
134
				"   <e2></e2>\n" + 
135
				"   <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + 
136
				"   <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + 
137
				"   <e5 xmlns=\"http://example.org\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + 
138
				"   <e6 xmlns:a=\"http://www.w3.org\">\n" + 
139
				"      <e7 xmlns=\"http://www.ietf.org\">\n" + 
140
				"         <e8 xmlns=\"\">\n" + 
141
				"            <e9 xmlns:a=\"http://www.ietf.org\" attr=\"default\"></e9>\n" + 
142
				"         </e8>\n" + 
143
				"      </e7>\n" + 
144
				"   </e6>\n" + 
145
				"</doc>";
146
		XMLInputFactory im=XMLInputFactory.newInstance();
147
		//im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));
148
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));		
149
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
150
				C14n.cannoicalizeWithoutComments(reader,new C14nInclusive()));
151
		C14n c=new C14n(new C14nInclusive());
152
		reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
153
		reader=im.createFilteredReader(reader,c);
154
		while ((reader.getEventType())!=XMLStreamReader.END_DOCUMENT) {
155
			reader.next();
156
		}
157
		assertEquals("Output not like stated in 3.1 rfc",outWithoutComments,
158
				c.getResult());
159
		
160
		
161
		
162
	}
163
164
	
165
	protected void setUp() throws Exception {
166
		super.setUp();
167
	}
168
169
}
(-)src_unitTests/com/r_bg/stax/c14n/C14nExcl.java (+29 lines)
Line 0 Link Here
1
package com.r_bg.stax.c14n;
2
3
import java.io.ByteArrayInputStream;
4
5
import javax.xml.stream.XMLInputFactory;
6
import javax.xml.stream.XMLStreamException;
7
import javax.xml.stream.XMLStreamReader;
8
9
import junit.framework.TestCase;
10
11
public class C14nExcl extends TestCase {
12
	public void testStandard() throws Exception {
13
		String in="<doc xmlns:a=\"http://a\">\n" + 
14
				" <a:a xmlns=\"http://a\">\n" + 
15
				"  <b/>\n" + 
16
				" </a:a>\n" + 
17
				"</doc>";
18
		String out="<doc>\n" + 
19
				" <a:a xmlns:a=\"http://a\">\n" + 
20
				"  <b xmlns=\"http://a\"></b>\n" + 
21
				" </a:a>\n" + 
22
				"</doc>";
23
		XMLInputFactory im=XMLInputFactory.newInstance();		
24
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));		
25
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
26
		assertEquals("mismath",out,
27
				C14n.cannoicalizeWithoutComments(reader,new AttributeHandleExclusive()));
28
	}
29
}
(-)src_unitTests/com/r_bg/stax/XMLSignatureTest.java (+288 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import java.io.ByteArrayInputStream;
4
import java.math.BigInteger;
5
import java.security.KeyFactory;
6
import java.security.NoSuchAlgorithmException;
7
import java.security.PublicKey;
8
import java.security.cert.CertificateException;
9
import java.security.cert.CertificateFactory;
10
import java.security.cert.X509Certificate;
11
import java.security.interfaces.RSAPublicKey;
12
import java.security.spec.InvalidKeySpecException;
13
import java.security.spec.RSAPublicKeySpec;
14
15
import javax.xml.crypto.KeySelector;
16
import javax.xml.crypto.XMLStructure;
17
import javax.xml.crypto.dsig.Reference;
18
import javax.xml.crypto.dsig.XMLSignature;
19
import javax.xml.crypto.dsig.XMLSignatureFactory;
20
import javax.xml.crypto.dsig.XMLValidateContext;
21
import javax.xml.stream.XMLInputFactory;
22
import javax.xml.stream.XMLStreamException;
23
import javax.xml.stream.XMLStreamReader;
24
25
import org.apache.xml.security.Init;
26
import org.apache.xml.security.exceptions.Base64DecodingException;
27
import org.apache.xml.security.exceptions.XMLSecurityException;
28
import org.apache.xml.security.keys.content.x509.XMLX509Certificate;
29
import org.apache.xml.security.utils.Base64;
30
import org.apache.xml.security.utils.Constants;
31
32
import sun.security.rsa.RSAKeyFactory;
33
import sun.security.x509.X509Cert;
34
35
import junit.framework.TestCase;
36
37
public class XMLSignatureTest extends TestCase {
38
	 /** @inheritDoc */
39
	public static PublicKey getPublicKey(String certS)  {
40
		
41
	      try {
42
	    	  CertificateFactory certFact =
43
	              CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID);
44
	    	  X509Certificate cert =
45
	              (X509Certificate) certFact
46
	                 .generateCertificate(new ByteArrayInputStream(
47
	                		 Base64.decode(certS.getBytes())) );
48
49
	           if (cert != null) {
50
	              return cert.getPublicKey();
51
	           }	      
52
		} catch (CertificateException e) {
53
			// TODO Auto-generated catch block
54
			e.printStackTrace();
55
		} catch (Base64DecodingException e) {
56
			// TODO Auto-generated catch block
57
			e.printStackTrace();
58
		}
59
	      return null;
60
	   }
61
	
62
	public static PublicKey getPublicKey(String data,String exp)  {
63
		
64
	      try {
65
	         KeyFactory rsaFactory = KeyFactory.getInstance("RSA");
66
	         // KeyFactory rsaFactory = KeyFactory.getInstance(JCE_RSA);
67
	         RSAPublicKeySpec rsaKeyspec =
68
	            new RSAPublicKeySpec(new BigInteger(1, Base64.decode(data.getBytes())),
69
	            		new BigInteger(1, Base64.decode(exp.getBytes())) );
70
	         PublicKey pk = rsaFactory.generatePublic(rsaKeyspec);
71
72
	         return pk;
73
	      } catch (NoSuchAlgorithmException ex) {
74
	    	  ex.printStackTrace();
75
	      } catch (InvalidKeySpecException ex) {
76
	    	  ex.printStackTrace();
77
	      } catch (Base64DecodingException e) {
78
			// TODO Auto-generated catch block
79
			e.printStackTrace();
80
		}
81
	      return null;
82
	   }
83
	public void testEnvelopedSignature() throws Exception {
84
		String in="<RootObject><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
85
         "<ds:SignedInfo>\n" + 
86
         "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:CanonicalizationMethod>\n" + 
87
         "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n" + 
88
         "<ds:Reference URI=\"#1\">\n" + 
89
         "<ds:Transforms>\n" + 
90
         "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:Transform>\n" + 
91
         "</ds:Transforms>\n" + 
92
         "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>\n" + 
93
         "<ds:DigestValue>oMQoFufPA7Un6cfz0GaEOJpE4Z8=</ds:DigestValue>\n" + 
94
         "</ds:Reference>\n" + 
95
         "</ds:SignedInfo>\n" + 
96
         "<ds:SignatureValue>\n" + 
97
         "AhyiFQ6hucykYJOJDBV3wbPBe2TAURXXfCUD7BmSAecT+izT9fHFsxRVez3s+6hYSgtaVhmeVgbd\n" + 
98
         "ZEOMPFihBGldi1NV73Z/tpXxqNvY+/NwQmmasQp9gzFHxYF2cqi8m7sAHM03BIC1YoBctxVw/jxV\n" + 
99
         "ClhLJuTSHoKwlzKH24g=\n" + 
100
         "</ds:SignatureValue>\n" + 
101
         "<ds:KeyInfo>\n" + 
102
         "<ds:KeyValue>\n" + 
103
         "<ds:RSAKeyValue>\n" + 
104
         "<ds:Modulus>\n" + 
105
         "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
106
         "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
107
         "VjevEfohDpn/+oxljm0=\n" + 
108
         "</ds:Modulus>\n" + 
109
         "<ds:Exponent>AQAB</ds:Exponent>\n" + 
110
         "</ds:RSAKeyValue>\n" + 
111
         "</ds:KeyValue>\n" + 
112
         "</ds:KeyInfo>\n" + 
113
         "<ds:Object Id=\"1\"><UnderObject>A text in a box<OtherObject><OtherObject2></OtherObject2><OtherObject6></OtherObject6><OtherObject></OtherObject></OtherObject></UnderObject></ds:Object>\n" + 
114
         "</ds:Signature></RootObject>";
115
		XMLInputFactory im=XMLInputFactory.newInstance();		
116
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));		
117
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
118
		StaxValidateContext stx = StaxValidateContext.createEnvelopedValidator(reader);		
119
		reader=im.createFilteredReader(reader, stx.getStreamReader());
120
		while ((reader.getEventType())!=XMLStreamReader.END_DOCUMENT) {
121
			reader.next();
122
		}		
123
		XMLSignatureFactory fac=XMLSignatureFactory.getInstance("Stax");
124
		stx.setSignatureNumber(0);
125
		XMLSignature sig=fac.unmarshalXMLSignature(stx);		
126
		assertTrue("Signature reference must be right",
127
				((Reference)sig.getSignedInfo().getReferences().get(0)).validate(stx));
128
		RSAPublicKey pl=(RSAPublicKey) getPublicKey(
129
		 "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
130
         "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
131
         "VjevEfohDpn/+oxljm0=\n" ,
132
         "AQAB"
133
         );
134
		stx.setKeySelector(KeySelector.singletonKeySelector(pl));
135
		assertTrue("Signature must be right",
136
				sig.validate(stx));
137
	}
138
	public void testTamperedEnvelopedSignature() throws Exception {
139
		String in="<RootObject><ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" +
140
         "<ds:SignedInfo>\n" + 
141
         "<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:CanonicalizationMethod>\n" + 
142
         "<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\"></ds:SignatureMethod>\n" + 
143
         "<ds:Reference URI=\"#1\">\n" + 
144
         "<ds:Transforms>\n" + 
145
         "<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"></ds:Transform>\n" + 
146
         "</ds:Transforms>\n" + 
147
         "<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\"></ds:DigestMethod>\n" + 
148
         "<ds:DigestValue>oMQoFufPA7Un6cfz0GaEOJpE4Z8=</ds:DigestValue>\n" + 
149
         "</ds:Reference>\n" + 
150
         "</ds:SignedInfo>\n" + 
151
         "<ds:SignatureValue>\n" + 
152
         "AhyiFQ6hucykYJOJDBV3wbPBe2TAURXXfCUD7BmSAecT+izT9fHFsxRVez3s+6hYSgtaVhmeVgbd\n" + 
153
         "ZEOMPFihBGldi1NV73Z/tpXxqNvY+/NwQmmasQp9gzFHxYF2cqi8m7sAHM03BIC1YoBctxVw/jxV\n" + 
154
         "ClhLJuTSHoKwlzKH24g=\n" + 
155
         "</ds:SignatureValue>\n" + 
156
         "<ds:KeyInfo>\n" + 
157
         "<ds:KeyValue>\n" + 
158
         "<ds:RSAKeyValue>\n" + 
159
         "<ds:Modulus>\n" + 
160
         "skqbW7oBwM1lCWNwC1obkgj4VV58G1AX7ERMWEIrQQlZ8uFdQ3FNkgMdtmx/XUjNF+zXTDmxe+K/\n" + 
161
         "lne+0KDwLWskqhS6gnkQmxZoR4FUovqRngoqU6bnnn0pM9gF/AI/vcdu7aowbF9S7TVlSw7IpxIQ\n" + 
162
         "VjevEfohDpn/+oxljm0=\n" + 
163
         "</ds:Modulus>\n" + 
164
         "<ds:Exponent>AQAB</ds:Exponent>\n" + 
165
         "</ds:RSAKeyValue>\n" + 
166
         "</ds:KeyValue>\n" + 
167
         "</ds:KeyInfo>\n" + 
168
         "<ds:Object Id=\"1\"><UnderObject>a text in a box<OtherObject><OtherObject2></OtherObject2><OtherObject6></OtherObject6><OtherObject></OtherObject></OtherObject></UnderObject></ds:Object>\n" + 
169
         "</ds:Signature></RootObject>";
170
		XMLInputFactory im=XMLInputFactory.newInstance();		
171
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));		
172
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
173
		StaxValidateContext stx = StaxValidateContext.createEnvelopedValidator(reader);		
174
		reader=im.createFilteredReader(reader, stx.getStreamReader());
175
		while ((reader.getEventType())!=XMLStreamReader.END_DOCUMENT) {
176
			reader.next();
177
		}		
178
		XMLSignatureFactory fac=XMLSignatureFactory.getInstance("Stax" );
179
		stx.setSignatureNumber(0);
180
		XMLSignature sig=fac.unmarshalXMLSignature(stx);
181
		assertFalse("Signature must be wrong",
182
				((Reference)sig.getSignedInfo().getReferences().get(0)).validate(stx));
183
	}
184
	public void testEnvelopingSignature() throws Exception{		
185
		String in="<?xml version=\"1.0\" encoding=\"UTF-8\"?><a>" +
186
				"<ns2:Assertion xmlns:ns2=\"urn:oasis:names:tc:SAML:2.0:assertion\" " +
187
				"ID=\"id3fe0b77e-c4a9-46db-be2f-c3a0d0a11d3f\" " +
188
				"IssueInstant=\"2006-05-23T11:20:28.750Z\" Version=\"2.0\">" +
189
				"<ns2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">" +
190
				"http://idp.idpdomain.com:9090/SAML2-IDP</ns2:Issuer>" +
191
				"<ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 				
192
				"<ds:SignedInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
193
				"<ds:CanonicalizationMethod Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
194
				"<ds:SignatureMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#rsa-sha1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
195
				"<ds:Reference URI=\"#id3fe0b77e-c4a9-46db-be2f-c3a0d0a11d3f\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
196
				"<ds:Transforms xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
197
				"<ds:Transform Algorithm=\"http://www.w3.org/2000/09/xmldsig#enveloped-signature\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
198
				"<ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
199
				"</ds:Transforms>\n" + 
200
				"<ds:DigestMethod Algorithm=\"http://www.w3.org/2000/09/xmldsig#sha1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\"/>\n" + 
201
				"<ds:DigestValue xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">KXIBvPvqtl/8btEq1NfAyOc1Rxg=</ds:DigestValue>\n" + 
202
				"</ds:Reference>\n" + 
203
				"</ds:SignedInfo>\n" + 
204
				"<ds:SignatureValue xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
205
				"WtI8wWrmgVfEzvMJWLynE7F1UniubZNrynuQnDrbXrW8G3v4G8EpaD46iNUwOyh6qTCl9bLtamtl\n" + 
206
				"jSiJkeWMLH0eTxlbLUHvftYHuvuM5QKue9sLGLJtbNC8AxyMThuG7Uz8MzZeu2vxffqXsGaWb3VQ\n" + 
207
				"F0vyS4IlEq4d+YduUQ0=\n" + 
208
				"</ds:SignatureValue>\n" + 
209
				"<ds:KeyInfo xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
210
				"<ds:X509Data xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
211
				"<ds:X509Certificate xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n" + 
212
				"MIICQjCCAasCBERCksgwDQYJKoZIhvcNAQEEBQAwaDELMAkGA1UEBhMCU1AxDzANBgNVBAgTBk1h\n" + 
213
				"ZHJpZDERMA8GA1UEBxMITWlsZW5pdW0xFTATBgNVBAoTDEZ1bmN0aW9uVGVzdDEMMAoGA1UECxMD\n" + 
214
				"RUlDMRAwDgYDVQQDEwdJRFBzaWduMB4XDTA2MDQxNjE4NTQwMFoXDTE2MDIyMzE4NTQwMFowaDEL\n" + 
215
				"MAkGA1UEBhMCU1AxDzANBgNVBAgTBk1hZHJpZDERMA8GA1UEBxMITWlsZW5pdW0xFTATBgNVBAoT\n" + 
216
				"DEZ1bmN0aW9uVGVzdDEMMAoGA1UECxMDRUlDMRAwDgYDVQQDEwdJRFBzaWduMIGfMA0GCSqGSIb3\n" + 
217
				"DQEBAQUAA4GNADCBiQKBgQCeSYE0gfeoTyXtqlBGn7NEqWVMAE+KzlMBW8apoASb41e7kxGGBc5y\n" + 
218
				"S4qLu5jMBwQTus9ctOhbMGnkonOvow7KC3axccsWc3cJt4aFGEbERJlhnwDmfa/Uk7qQ3aOmgl2P\n" + 
219
				"6vY40En+jj4j5PkSETZXvtGBELLVOkVdTIQwjQ5sRQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFbF\n" + 
220
				"npwJ4XEcIyWEkkdSb30CCQsvflxVtvurhS97HzZxN3zi24KllnqtmYixM5S8Lsvrbov9Jz6ZaYnR\n" + 
221
				"gD835oZDcSm/KKrRnFJxYxTjdbaolcEXyZU71v4JZMV6CMp9oLdyelYm08L6bacprw5VoF8sudQK\n" + 
222
				"+7svI9827YEMeGPb\n" + 
223
				"</ds:X509Certificate>\n" + 
224
				"</ds:X509Data>\n" + 
225
				"</ds:KeyInfo>\n" + 
226
				"</ds:Signature>" +
227
				"<ns2:Subject><ns2:NameID Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:persistent\" " +
228
				"NameQualifier=\"http://idp.idpdomain.com:9090/SAML2-IDP\" " +
229
				"SPNameQualifier=\"http://sp.spdomain.com:8080/SP1\" " +
230
				"SPProvidedID=\"FT5b5fc506-1b56-4cf3-ab8c-f904d9975f9e\">nida42d1765-d2c8-46b9-8568-c27eaddcd8a7" +
231
				"</ns2:NameID>" +
232
				"<ns2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">" +
233
				"<ns2:SubjectConfirmationData InResponseTo=\"FTde99c35d-f413-42fb-8a60-289b86d39ebe\"" +
234
				" NotOnOrAfter=\"2006-05-23T11:42:28.796Z\" Recipient=\"http://sp.spdomain.com:8080/SP1\"/>" +
235
				"</ns2:SubjectConfirmation></ns2:Subject>" +
236
				"<ns2:Conditions NotBefore=\"2006-05-23T11:17:28.796Z\" " +
237
				"NotOnOrAfter=\"2006-05-23T11:42:28.796Z\">" +
238
				"<ns2:AudienceRestriction>" +
239
				"<ns2:Audience>http://sp.spdomain.com:8080/SP1</ns2:Audience>" +
240
				"</ns2:AudienceRestriction></ns2:Conditions>" +
241
				"<ns2:AuthnStatement AuthnInstant=\"2006-05-23T11:20:27.593Z\" " +
242
				"SessionIndex=\"A202FAFB0C3C80E9B360741F6F493085\" SessionNotOnOrAfter=\"2006-05-23T11:42:28.796Z\">" +
243
				"<ns2:AuthnContext>" +
244
				"<ns2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password" +
245
				"</ns2:AuthnContextClassRef></ns2:AuthnContext></ns2:AuthnStatement>" +
246
				"</ns2:Assertion></a>";
247
		XMLInputFactory im=XMLInputFactory.newInstance();		
248
		im.setProperty("javax.xml.stream.supportDTD", new Boolean(false));	
249
		XMLStreamReader reader=im.createXMLStreamReader(new ByteArrayInputStream(in.getBytes()));
250
		StaxValidateContext stx = StaxValidateContext.createEnvelopedValidator(reader);	
251
		reader=im.createFilteredReader(reader, stx.getStreamReader());
252
		while ((reader.getEventType())!=XMLStreamReader.END_DOCUMENT) {
253
			if ((reader.getEventType()== XMLStreamReader.START_ELEMENT) && reader.getLocalName().equals("Assertion")) {
254
				stx.currentNodeIsReferenceTarget(reader.getAttributeValue(null, "ID"),null, "http://www.w3.org/2000/09/xmldsig#sha1");
255
			}
256
		
257
			reader.next();
258
		}
259
		XMLSignatureFactory fac=XMLSignatureFactory.getInstance("Stax" );
260
		stx.setSignatureNumber(0);
261
		XMLSignature sig=fac.unmarshalXMLSignature(stx);
262
		assertTrue("Signature must be correct",
263
				((Reference)sig.getSignedInfo().getReferences().get(0)).validate(stx));
264
		String cert="MIICQjCCAasCBERCksgwDQYJKoZIhvcNAQEEBQAwaDELMAkGA1UEBhMCU1AxDzANBgNVBAgTBk1h\n" + 
265
		"ZHJpZDERMA8GA1UEBxMITWlsZW5pdW0xFTATBgNVBAoTDEZ1bmN0aW9uVGVzdDEMMAoGA1UECxMD\n" + 
266
		"RUlDMRAwDgYDVQQDEwdJRFBzaWduMB4XDTA2MDQxNjE4NTQwMFoXDTE2MDIyMzE4NTQwMFowaDEL\n" + 
267
		"MAkGA1UEBhMCU1AxDzANBgNVBAgTBk1hZHJpZDERMA8GA1UEBxMITWlsZW5pdW0xFTATBgNVBAoT\n" + 
268
		"DEZ1bmN0aW9uVGVzdDEMMAoGA1UECxMDRUlDMRAwDgYDVQQDEwdJRFBzaWduMIGfMA0GCSqGSIb3\n" + 
269
		"DQEBAQUAA4GNADCBiQKBgQCeSYE0gfeoTyXtqlBGn7NEqWVMAE+KzlMBW8apoASb41e7kxGGBc5y\n" + 
270
		"S4qLu5jMBwQTus9ctOhbMGnkonOvow7KC3axccsWc3cJt4aFGEbERJlhnwDmfa/Uk7qQ3aOmgl2P\n" + 
271
		"6vY40En+jj4j5PkSETZXvtGBELLVOkVdTIQwjQ5sRQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAFbF\n" + 
272
		"npwJ4XEcIyWEkkdSb30CCQsvflxVtvurhS97HzZxN3zi24KllnqtmYixM5S8Lsvrbov9Jz6ZaYnR\n" + 
273
		"gD835oZDcSm/KKrRnFJxYxTjdbaolcEXyZU71v4JZMV6CMp9oLdyelYm08L6bacprw5VoF8sudQK\n" + 
274
		"+7svI9827YEMeGPb\n" ;
275
		RSAPublicKey pl=(RSAPublicKey) getPublicKey(cert);
276
				stx.setKeySelector(KeySelector.singletonKeySelector(pl));
277
				assertTrue("Signature must be right",
278
						sig.validate(stx));
279
	}
280
	
281
	static {		
282
		Init.init();
283
		
284
		StaxXMLSignatureFactory.getInstance("Stax", new StaxProvider());
285
286
	};
287
288
}
(-)src_unitTests/com/r_bg/stax/XMLEnvelopedTest.java (+7 lines)
Line 0 Link Here
1
package com.r_bg.stax;
2
3
import junit.framework.TestCase;
4
5
public class XMLEnvelopedTest extends TestCase {
6
7
}

Return to bug 39029