diff options
Diffstat (limited to 'bkucommon/src/test/java')
-rw-r--r-- | bkucommon/src/test/java/moaspss/MOASPClient.java | 276 | ||||
-rw-r--r-- | bkucommon/src/test/java/moaspss/MOASPSSTest.java | 119 | ||||
-rw-r--r-- | bkucommon/src/test/java/moaspss/SLClient.java | 175 | ||||
-rw-r--r-- | bkucommon/src/test/java/moaspss/SLException.java | 40 | ||||
-rw-r--r-- | bkucommon/src/test/java/moaspss/TestCreateAndVerifySignature.java | 163 |
5 files changed, 654 insertions, 119 deletions
diff --git a/bkucommon/src/test/java/moaspss/MOASPClient.java b/bkucommon/src/test/java/moaspss/MOASPClient.java new file mode 100644 index 00000000..ade5b38b --- /dev/null +++ b/bkucommon/src/test/java/moaspss/MOASPClient.java @@ -0,0 +1,276 @@ +/* +* Copyright 2008 Federal Chancellery Austria and +* Graz University of Technology +* +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ +package moaspss; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.net.URL; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.bind.SchemaOutputResolver; +import javax.xml.bind.Unmarshaller; +import javax.xml.bind.Validator; +import javax.xml.namespace.QName; +import javax.xml.transform.Result; + +import moaspss.generated.ContentOptionalRefType; +import moaspss.generated.InputDataType; +import moaspss.generated.MOAFault; +import moaspss.generated.ObjectFactory; +import moaspss.generated.SignatureVerificationPortType; +import moaspss.generated.SignatureVerificationService; +import moaspss.generated.VerifyXMLSignatureRequestType; +import moaspss.generated.VerifyXMLSignatureResponseType; +import moaspss.generated.VerifyXMLSignatureRequestType.VerifySignatureInfo; + +import org.w3c.dom.Node; +import org.w3c.dom.bootstrap.DOMImplementationRegistry; +import org.w3c.dom.ls.DOMImplementationLS; +import org.w3c.dom.ls.LSOutput; +import org.w3c.dom.ls.LSSerializer; + +import com.sun.xml.bind.api.Bridge; +import com.sun.xml.bind.api.BridgeContext; +import com.sun.xml.bind.api.JAXBRIContext; +import com.sun.xml.bind.api.RawAccessor; +import com.sun.xml.bind.api.TypeReference; +import com.sun.xml.bind.marshaller.NamespacePrefixMapper; +import com.sun.xml.ws.api.model.SEIModel; +import com.sun.xml.ws.developer.JAXBContextFactory; +import com.sun.xml.ws.developer.UsesJAXBContextFeature; + +@SuppressWarnings("deprecation") +public class MOASPClient { + + private static class JAXBContextHolder { + + private static final JAXBContext context; + + static { + try { + context = JAXBRIContext.newInstance(VerifyXMLSignatureRequestType.class.getPackage().getName()); + } catch (JAXBException e) { + throw new RuntimeException("Failed to setup JAXBContext.", e); + } + } + + } + + public static JAXBContext getJAXBContext() { + return JAXBContextHolder.context; + } + + public static class ClientJAXBContextFactory implements JAXBContextFactory { + + @SuppressWarnings("unchecked") + public JAXBRIContext createJAXBContext(final SEIModel sei, + final List<Class> classesToBind, final List<TypeReference> typeReferences) + throws JAXBException { + + System.out.println("Create Context"); + + return new JAXBRIContext() { + + JAXBRIContext context = JAXBRIContext.newInstance(classesToBind.toArray + (new Class[classesToBind.size()]), + typeReferences, null, sei.getTargetNamespace(), false, null); + + @Override + public Validator createValidator() throws JAXBException { + return context.createValidator(); + } + + @Override + public Unmarshaller createUnmarshaller() throws JAXBException { + return context.createUnmarshaller(); + } + + @Override + public Marshaller createMarshaller() throws JAXBException { + Marshaller marshaller = context.createMarshaller(); + ClientNamespacePrefixMapper pm = new ClientNamespacePrefixMapper(); + System.out.println(pm.toString()); + marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", pm); + return marshaller; + } + + @Override + public boolean hasSwaRef() { + return context.hasSwaRef(); + } + + @Override + public QName getTypeName(TypeReference arg0) { + return context.getTypeName(arg0); + } + + @Override + public List<String> getKnownNamespaceURIs() { + return context.getKnownNamespaceURIs(); + } + + @Override + public <B, V> RawAccessor<B, V> getElementPropertyAccessor(Class<B> arg0, + String arg1, String arg2) throws JAXBException { + return context.getElementPropertyAccessor(arg0, arg1, arg2); + } + + @Override + public QName getElementName(Object arg0) throws JAXBException { + return context.getElementName(arg0); + } + + @Override + public String getBuildId() { + return context.getBuildId(); + } + + @Override + public void generateSchema(SchemaOutputResolver arg0) throws IOException { + context.generateSchema(arg0); + } + + @Override + public void generateEpisode(Result arg0) { + context.generateEpisode(arg0); + } + + @Override + public BridgeContext createBridgeContext() { + return context.createBridgeContext(); + } + + @Override + public Bridge createBridge(TypeReference arg0) { + return context.createBridge(arg0); + } + }; + + } + + } + + public static class ClientNamespacePrefixMapper extends NamespacePrefixMapper { + + protected static final Map<String, String> prefixMap = new HashMap<String, String>(); + + static { + prefixMap.put("http://www.w3.org/2001/XMLSchema-instance", "xsi"); + prefixMap.put("http://reference.e-government.gv.at/namespace/moa/20020822#", "moa"); + prefixMap.put("http://www.w3.org/2000/09/xmldsig#", "dsig"); + prefixMap.put("http://uri.etsi.org/01903/v1.1.1#", "xades"); + } + + + @Override + public String getPreferredPrefix(String namespaceUri, String suggestion, boolean requirePrefix) { + + String prefix = prefixMap.get(namespaceUri); + + return (prefix != null) ? prefix : suggestion; + } + + /** + * Returns a list of namespace URIs that should be declared + * at the root element. + * <p> + * By default, the JAXB RI produces namespace declarations only when + * they are necessary, only at where they are used. Because of this + * lack of look-ahead, sometimes the marshaller produces a lot of + * namespace declarations that look redundant to human eyes. For example, + */ + @Override + public String[] getPreDeclaredNamespaceUris() { + return new String[]{ "http://www.w3.org/2000/09/xmldsig#" }; + } + } + + + private SignatureVerificationPortType port; + + public MOASPClient() { + QName serviceName = new QName("http://reference.e-government.gv.at/namespace/moa/wsdl/20020822#", "SignatureVerificationService"); + + URL wsdlURL = MOASPClient.class.getClassLoader().getResource("MOA-SPSS-1.3.wsdl"); + + SignatureVerificationService service = new SignatureVerificationService(wsdlURL, serviceName); + + UsesJAXBContextFeature feature = new UsesJAXBContextFeature(ClientJAXBContextFactory.class); + + port = service.getSignatureVerificationPort(feature); + } + + public JAXBElement<VerifyXMLSignatureResponseType> verifySignature(Node node, + String signatureLocation, String trustProfileId) throws JAXBException, + IOException, ClassCastException, ClassNotFoundException, + InstantiationException, IllegalAccessException { + + DOMImplementationLS domImpl = (DOMImplementationLS) DOMImplementationRegistry + .newInstance().getDOMImplementation("LS"); + + LSSerializer serializer = domImpl.createLSSerializer(); + + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + LSOutput output = domImpl.createLSOutput(); + output.setByteStream(bos); + serializer.write(node, output); + + ObjectFactory factory = new ObjectFactory(); + + ContentOptionalRefType contentOptionalRefType = factory.createContentOptionalRefType(); + contentOptionalRefType.setBase64Content(bos.toByteArray()); + + VerifySignatureInfo verifySignatureInfo = factory.createVerifyXMLSignatureRequestTypeVerifySignatureInfo(); + verifySignatureInfo.setVerifySignatureEnvironment(contentOptionalRefType); + verifySignatureInfo.setVerifySignatureLocation(signatureLocation); + + VerifyXMLSignatureRequestType verifyXMLSignatureRequestType = factory.createVerifyXMLSignatureRequestType(); + verifyXMLSignatureRequestType.setVerifySignatureInfo(verifySignatureInfo); + verifyXMLSignatureRequestType.setTrustProfileID(trustProfileId); + verifyXMLSignatureRequestType.setReturnHashInputData(Boolean.TRUE); + + VerifyXMLSignatureResponseType resp = null; + try { + resp = port.verifyXMLSignature(verifyXMLSignatureRequestType); + } catch (MOAFault e) { + e.printStackTrace(); + } + + JAXBElement<VerifyXMLSignatureResponseType> verifyXMLSignatureResponse = factory.createVerifyXMLSignatureResponse(resp); + + Marshaller marshaller = getJAXBContext().createMarshaller(); + marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); + marshaller.marshal(verifyXMLSignatureResponse, System.out); + + List<InputDataType> hashInputData = resp.getHashInputData(); + for (InputDataType inputDataType : hashInputData) { + System.out.println("------------------------------------------"); + System.out.println("HashInputData: " + inputDataType.getPartOf() + " " + inputDataType.getReferringSigReference()); + System.out.println("------------------------------------------"); + System.out.write(inputDataType.getBase64Content()); + System.out.println(); + } + + return verifyXMLSignatureResponse; + } +} diff --git a/bkucommon/src/test/java/moaspss/MOASPSSTest.java b/bkucommon/src/test/java/moaspss/MOASPSSTest.java deleted file mode 100644 index 21d42176..00000000 --- a/bkucommon/src/test/java/moaspss/MOASPSSTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright 2008 Federal Chancellery Austria and -* Graz University of Technology -* -* Licensed under the Apache License, Version 2.0 (the "License"); -* you may not use this file except in compliance with the License. -* You may obtain a copy of the License at -* -* http://www.apache.org/licenses/LICENSE-2.0 -* -* Unless required by applicable law or agreed to in writing, software -* distributed under the License is distributed on an "AS IS" BASIS, -* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -* See the License for the specific language governing permissions and -* limitations under the License. -*/ -package moaspss; - -import static org.junit.Assert.assertNotNull; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; - -import javax.xml.bind.JAXBContext; -import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; -import javax.xml.bind.Marshaller; -import javax.xml.namespace.QName; - -import moaspss.generated.ContentOptionalRefType; -import moaspss.generated.InputDataType; -import moaspss.generated.MOAFault; -import moaspss.generated.ObjectFactory; -import moaspss.generated.SignatureVerificationPortType; -import moaspss.generated.SignatureVerificationService; -import moaspss.generated.VerifyXMLSignatureRequestType; -import moaspss.generated.VerifyXMLSignatureResponseType; -import moaspss.generated.VerifyXMLSignatureRequestType.VerifySignatureInfo; - -import org.junit.BeforeClass; -import org.junit.Ignore; -import org.junit.Test; - -@Ignore -public class MOASPSSTest { - - public static final String REQ_FILE = "TODO.xml"; - private static JAXBContext ctx; - private static SignatureVerificationPortType port; - - @BeforeClass - public static void setUp() throws JAXBException, MalformedURLException { - QName serviceName = new QName("http://reference.e-government.gv.at/namespace/moa/wsdl/20020822#", "SignatureVerificationService"); - - URL wsdlURL = MOASPSSTest.class.getClassLoader().getResource("MOA-SPSS-1.3.wsdl"); - - assertNotNull(wsdlURL); - - SignatureVerificationService service = new SignatureVerificationService(wsdlURL, serviceName); - - port = service.getSignatureVerificationPort(); - assertNotNull(port); - ctx = JAXBContext.newInstance(VerifyXMLSignatureRequestType.class.getPackage().getName()); - } - - @Test - public void verifySignature() throws JAXBException, IOException { - - InputStream stream = MOASPSSTest.class.getClassLoader().getResourceAsStream("Untitled1.xml"); - assertNotNull(stream); - - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - int b; - while ((b = stream.read()) != -1) { - bos.write(b); - } - stream.close(); - - ObjectFactory factory = new ObjectFactory(); - - ContentOptionalRefType contentOptionalRefType = factory.createContentOptionalRefType(); - contentOptionalRefType.setBase64Content(bos.toByteArray()); - - VerifySignatureInfo verifySignatureInfo = factory.createVerifyXMLSignatureRequestTypeVerifySignatureInfo(); - verifySignatureInfo.setVerifySignatureEnvironment(contentOptionalRefType); - verifySignatureInfo.setVerifySignatureLocation("/child::*[1]/child::*[2]"); - - VerifyXMLSignatureRequestType verifyXMLSignatureRequestType = factory.createVerifyXMLSignatureRequestType(); - verifyXMLSignatureRequestType.setVerifySignatureInfo(verifySignatureInfo); - verifyXMLSignatureRequestType.setTrustProfileID("IdentityLink"); - verifyXMLSignatureRequestType.setReturnHashInputData(Boolean.TRUE); - - VerifyXMLSignatureResponseType resp = null; - try { - resp = port.verifyXMLSignature(verifyXMLSignatureRequestType); - } catch (MOAFault e) { - e.printStackTrace(); - } - - JAXBElement<VerifyXMLSignatureResponseType> verifyXMLSignatureResponse = factory.createVerifyXMLSignatureResponse(resp); - - Marshaller marshaller = ctx.createMarshaller(); - marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); - marshaller.marshal(verifyXMLSignatureResponse, System.out); - - List<InputDataType> hashInputData = resp.getHashInputData(); - for (InputDataType inputDataType : hashInputData) { - System.out.println("------------------------------------------"); - System.out.println("HashInputData: " + inputDataType.getPartOf() + " " + inputDataType.getReferringSigReference()); - System.out.println("------------------------------------------"); - System.out.write(inputDataType.getBase64Content()); - System.out.println(); - } - } -} diff --git a/bkucommon/src/test/java/moaspss/SLClient.java b/bkucommon/src/test/java/moaspss/SLClient.java new file mode 100644 index 00000000..c3561bfe --- /dev/null +++ b/bkucommon/src/test/java/moaspss/SLClient.java @@ -0,0 +1,175 @@ +package moaspss; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.OutputStreamWriter; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.net.HttpURLConnection; +import java.net.MalformedURLException; +import java.net.ProtocolException; +import java.net.URL; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.Result; +import javax.xml.transform.Source; +import javax.xml.transform.Transformer; +import javax.xml.transform.TransformerException; +import javax.xml.transform.TransformerFactory; +import javax.xml.transform.dom.DOMSource; +import javax.xml.transform.stream.StreamResult; + +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; + +import at.gv.egiz.bku.utils.URLEncodingWriter; + +public class SLClient { + + private static class JAXBContextHolder { + + private static JAXBContext context; + + { + String slPkg = at.buergerkarte.namespaces.securitylayer._1.ObjectFactory.class.getPackage().getName(); + String xmldsigPkg = org.w3._2000._09.xmldsig_.ObjectFactory.class.getPackage().getName(); + String samlPkg = oasis.names.tc.saml._1_0.assertion.ObjectFactory.class.getPackage().getName(); + String prPkg = at.buergerkarte.namespaces.personenbindung._20020506_.ObjectFactory.class.getPackage().getName(); + try { + context = JAXBContext.newInstance(slPkg + ":" + xmldsigPkg + ":" + samlPkg + ":" + prPkg); + } catch (JAXBException e) { + throw new RuntimeException("Failed to setup JAXBContext.", e); + } + } + + } + + public static JAXBContext getJAXBContext() { + return JAXBContextHolder.context; + } + + private URL slUrl; + + private URL slUrlSSL; + + private boolean useSSL = false; + + public SLClient() { + try { + slUrl = new URL("http://localhost:3495/http-security-layer-request"); + slUrlSSL = new URL("https://localhost:3496/https-security-layer-request"); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } + + public Object submitRequest(Element request, Class<?> responseType) + throws SLException, TransformerException, IOException { + + URL url = (useSSL) ? slUrlSSL : slUrl; + + HttpURLConnection connection; + int responseCode; + try { + connection = (HttpURLConnection) url.openConnection(); + connection.setRequestMethod("POST"); + connection.setDoOutput(true); + connection.setDoInput(true); + connection.connect(); + + OutputStream outputStream = connection.getOutputStream(); + OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream, "ISO-8859-1"); + streamWriter.write("XMLRequest="); + URLEncodingWriter urlEnc = new URLEncodingWriter(streamWriter); + + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer transformer = tf.newTransformer(); + Source source = new DOMSource(request); + Result result = new StreamResult(urlEnc); + transformer.transform(source, result); + urlEnc.flush(); + streamWriter.flush(); + outputStream.close(); + responseCode = connection.getResponseCode(); + + } catch (ProtocolException e) { + throw new RuntimeException(e); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + + if (responseCode == 200) { + String[] contentType = connection.getContentType().split(";", 2); + + if ("text/xml".equals(contentType[0])) { + + Reader streamReader; + try { + InputStream inputStream = connection.getInputStream(); + + String charset = "ISO-8859-1"; + if (contentType.length > 1 + && (contentType[1].trim()).startsWith("charset=")) { + charset = contentType[1].split("=", 2)[1]; + } + + streamReader = new InputStreamReader(inputStream, charset); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + + if (JAXBElement.class.isAssignableFrom(responseType)) { + Object obj; + try { + Unmarshaller unmarshaller = getJAXBContext().createUnmarshaller(); + obj = unmarshaller.unmarshal(streamReader); + } catch (JAXBException e) { + throw new SLException(9000, e); + } + if (obj instanceof JAXBElement<?>) { + return obj; + } else { + throw new SLException(9000, "Got unexpected response."); + } + } else if (Element.class.isAssignableFrom(responseType)) { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document doc; + try { + DocumentBuilder db = dbf.newDocumentBuilder(); + doc = db.parse(new InputSource(streamReader)); + } catch (ParserConfigurationException e) { + throw new SLException(9000, e); + } catch (SAXException e) { + throw new SLException(9000, e); + } catch (IOException e) { + throw new SLException(9000, e); + } + return doc.getDocumentElement(); + } else { + throw new SLException(9000, "Unsupported response type " + + responseType); + } + + } else { + throw new SLException(9000, "Got unexpected content type " + + contentType + "."); + } + } else { + throw new SLException(9000, "Got unexpected response code " + + responseCode + "."); + } + + } + +} diff --git a/bkucommon/src/test/java/moaspss/SLException.java b/bkucommon/src/test/java/moaspss/SLException.java new file mode 100644 index 00000000..4b43d6e7 --- /dev/null +++ b/bkucommon/src/test/java/moaspss/SLException.java @@ -0,0 +1,40 @@ +package moaspss; + +public class SLException extends Exception { + + private static final long serialVersionUID = 1L; + + private int code; + + private String info; + + public SLException() { + super(); + } + + public SLException(int code, String info) { + super(code + ": " + info); + this.code = code; + this.info = info; + } + + public SLException(Throwable cause, int code, String info) { + super(code + ": " + info, cause); + this.code = code; + this.info = info; + } + + public SLException(int code, Throwable cause) { + super(code + ": " + cause.getMessage(), cause); + this.code = code; + } + + public int getCode() { + return code; + } + + public String getInfo() { + return info; + } + +} diff --git a/bkucommon/src/test/java/moaspss/TestCreateAndVerifySignature.java b/bkucommon/src/test/java/moaspss/TestCreateAndVerifySignature.java new file mode 100644 index 00000000..8d995530 --- /dev/null +++ b/bkucommon/src/test/java/moaspss/TestCreateAndVerifySignature.java @@ -0,0 +1,163 @@ +package moaspss; + +import static junit.framework.Assert.fail; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.util.Iterator; + +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; +import javax.xml.transform.TransformerException; + +import moaspss.generated.KeyInfoType; +import moaspss.generated.VerifyXMLSignatureResponseType; +import moaspss.generated.X509DataType; + +import org.junit.Ignore; +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.DocumentFragment; +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.SAXException; + +import at.buergerkarte.namespaces.securitylayer._1.ErrorResponseType; + +@Ignore +public class TestCreateAndVerifySignature { + + protected Element parseCreateXMLSignatureRequest(InputStream is) + throws ParserConfigurationException, SAXException, IOException { + + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + Document doc; + DocumentBuilder db = dbf.newDocumentBuilder(); + doc = db.parse(is); + + Element docElem = doc.getDocumentElement(); + if ("http://www.buergerkarte.at/namespaces/securitylayer/1.2#".equals(docElem.getNamespaceURI()) + && "CreateXMLSignatureRequest".equals(docElem.getLocalName())) { + return docElem; + } else { + return null; + } + + } + + protected DocumentFragment getXMLSignatureFromResponse(String xpath, Object response) throws SLException, JAXBException { + + if (response instanceof Element) { + + Element respElem = (Element) response; + if ("http://www.buergerkarte.at/namespaces/securitylayer/1.2#".equals(respElem.getNamespaceURI()) + && "CreateXMLSignatureResponse".equals(respElem.getLocalName())) { + + NodeList childNodes = respElem.getChildNodes(); + + Document doc = respElem.getOwnerDocument(); + DocumentFragment fragment = doc.createDocumentFragment(); + + for (int i = 0; i < childNodes.getLength(); i++) { + fragment.appendChild(childNodes.item(i)); + } + + return fragment; + + } else { + Unmarshaller unmarshaller = SLClient.getJAXBContext().createUnmarshaller(); + Object obj = unmarshaller.unmarshal(respElem); + + if (obj instanceof JAXBElement<?>) { + JAXBElement<?> element = (JAXBElement<?>) obj; + if (element.getValue() instanceof ErrorResponseType) { + ErrorResponseType error = (ErrorResponseType) element.getValue(); + throw new SLException(error.getErrorCode(), error.getInfo()); + } + } + } + } + + return null; + + } + + public X509Certificate getCertFromKeyInfo(KeyInfoType keyInfo) throws CertificateException { + + Iterator<Object> keyInfos = keyInfo.getContent().iterator(); + while (keyInfos.hasNext()) { + Object ki = keyInfos.next(); + if (ki instanceof JAXBElement<?> + && X509DataType.class.isAssignableFrom(((JAXBElement<?>) ki) + .getDeclaredType())) { + X509DataType x509data = (X509DataType) ((JAXBElement<?>) ki).getValue(); + Iterator<Object> contents = x509data + .getX509IssuerSerialOrX509SKIOrX509SubjectName().iterator(); + while (contents.hasNext()) { + Object content = (Object) contents.next(); + if (byte[].class.isAssignableFrom(((JAXBElement<?>) content) + .getDeclaredType())) { + CertificateFactory certFactory = CertificateFactory.getInstance("X509"); + byte[] b = (byte[]) ((JAXBElement<?>) content).getValue(); + return (X509Certificate) certFactory.generateCertificate(new ByteArrayInputStream(b)); + } + } + + } + } + + return null; + + } + + @Test + public void testCreateAndVerifyXMLSignature() + throws ParserConfigurationException, SAXException, IOException, + TransformerException, JAXBException, ClassCastException, + ClassNotFoundException, InstantiationException, IllegalAccessException, CertificateException { + + ClassLoader cl = TestCreateAndVerifySignature.class.getClassLoader(); + InputStream is = cl.getResourceAsStream("moaspss/CreateXMLSignatureRequest.xml"); + Element cxsReq = parseCreateXMLSignatureRequest(is); + + Node cxsResp; + try { + SLClient slClient = new SLClient(); + Object response = slClient.submitRequest(cxsReq, Element.class); + cxsResp = getXMLSignatureFromResponse(".", response); + } catch (SLException e) { + fail(e.getMessage()); + return; + } + + MOASPClient spClient = new MOASPClient(); + JAXBElement<VerifyXMLSignatureResponseType> verifySignature = spClient.verifySignature(cxsResp, ".", "qualifiedSignature"); + VerifyXMLSignatureResponseType vxsResp = verifySignature.getValue(); + int signatureCheck = vxsResp.getSignatureCheck().getCode().intValue(); + if (signatureCheck != 0) { + fail("SignatureCheck = " + signatureCheck); + } + int certificateCheck = vxsResp.getCertificateCheck().getCode().intValue(); + if (certificateCheck != 0) { + + X509Certificate certificate = getCertFromKeyInfo(vxsResp.getSignerInfo()); + if (certificate != null) { + System.out.println(certificate); + } + + fail("CertificateCheck = " + certificateCheck); + } + + } + +} |