From b1c8641a63a67e3c64d948f9e8dce5c01e11e2dd Mon Sep 17 00:00:00 2001 From: mcentner Date: Wed, 5 May 2010 15:29:01 +0000 Subject: Merged feature branch mocca-1.2.13-id@r724 back to trunk. git-svn-id: https://joinup.ec.europa.eu/svn/mocca/trunk@725 8a26b1a7-26f0-462f-b9ef-d0e30c41f5a4 --- .../impl/xsect/AlgorithmMethodFactoryImpl.java | 3 +- .../egiz/bku/slcommands/impl/xsect/DataObject.java | 191 +++++----- .../slcommands/impl/xsect/LocRefDereferencer.java | 189 +++++----- .../bku/slcommands/impl/xsect/STALPrivateKey.java | 3 +- .../bku/slcommands/impl/xsect/STALProvider.java | 71 ---- .../bku/slcommands/impl/xsect/STALSignature.java | 184 --------- .../impl/xsect/STALSignatureException.java | 2 +- .../slcommands/impl/xsect/STALSignatureMethod.java | 127 +++++++ .../egiz/bku/slcommands/impl/xsect/Signature.java | 43 +-- .../slcommands/impl/xsect/SignatureContext.java | 50 +-- .../slcommands/impl/xsect/SignatureLocation.java | 418 ++++++++++----------- .../impl/xsect/URIDereferncerAdapter.java | 14 +- 12 files changed, 589 insertions(+), 706 deletions(-) delete mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java delete mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java create mode 100644 bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureMethod.java (limited to 'bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect') diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java index 8391e450..f1219a6c 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/AlgorithmMethodFactoryImpl.java @@ -165,8 +165,7 @@ public class AlgorithmMethodFactoryImpl implements AlgorithmMethodFactory { public SignatureMethod createSignatureMethod(SignatureContext signatureContext) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { - return signatureContext.getSignatureFactory().newSignatureMethod( - signatureAlgorithmURI, signatureMethodParameterSpec); + return new STALSignatureMethod(signatureAlgorithmURI, signatureMethodParameterSpec); } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java index 2cae41d6..a3f913de 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/DataObject.java @@ -20,11 +20,13 @@ import iaik.xml.crypto.dom.DOMCryptoContext; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; +import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.SequenceInputStream; import java.io.StringWriter; import java.io.UnsupportedEncodingException; +import java.net.URI; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.security.InvalidAlgorithmParameterException; @@ -36,6 +38,9 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import javax.xml.bind.JAXBElement; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; import javax.xml.crypto.MarshalException; import javax.xml.crypto.dom.DOMStructure; import javax.xml.crypto.dsig.CanonicalizationMethod; @@ -46,15 +51,17 @@ import javax.xml.crypto.dsig.XMLObject; import javax.xml.crypto.dsig.spec.TransformParameterSpec; import javax.xml.crypto.dsig.spec.XPathFilter2ParameterSpec; import javax.xml.crypto.dsig.spec.XPathType; +import javax.xml.namespace.QName; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.DOMException; 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.w3c.dom.Text; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; @@ -70,6 +77,7 @@ import at.buergerkarte.namespaces.securitylayer._1.MetaInfoType; import at.buergerkarte.namespaces.securitylayer._1.TransformsInfoType; import at.gv.egiz.bku.binding.HttpUtil; import at.gv.egiz.bku.gui.viewer.MimeTypes; +import at.gv.egiz.bku.slcommands.SLMarshallerFactory; import at.gv.egiz.bku.slexceptions.SLCommandException; import at.gv.egiz.bku.slexceptions.SLRequestException; import at.gv.egiz.bku.slexceptions.SLRuntimeException; @@ -81,10 +89,6 @@ import at.gv.egiz.bku.viewer.Validator; import at.gv.egiz.bku.viewer.ValidatorFactory; import at.gv.egiz.dom.DOMUtils; import at.gv.egiz.slbinding.impl.XMLContentType; -import java.io.File; -import java.net.MalformedURLException; -import java.net.URI; -import java.net.URL; /** * This class represents a DataObject of an XML-Signature @@ -97,7 +101,7 @@ public class DataObject { /** * Logging facility. */ - private static Log log = LogFactory.getLog(DataObject.class); + private final Logger log = LoggerFactory.getLogger(DataObject.class); /** * DOM Implementation. @@ -205,7 +209,7 @@ public class DataObject { domImplLS = (DOMImplementationLS) registry.getDOMImplementation(DOM_LS_3_0); if (domImplLS == null) { - log.error("Failed to get DOMImplementation " + DOM_LS_3_0); + log.error("Failed to get DOMImplementation {}.", DOM_LS_3_0); throw new SLRuntimeException("Failed to get DOMImplementation " + DOM_LS_3_0); } @@ -276,7 +280,7 @@ public class DataObject { try { validator = ValidatorFactory.newValidator(mediaType); } catch (IllegalArgumentException e) { - log.error("No validator found for mime type '" + mediaType + "'."); + log.error("No validator found for mime type '{}'.", mediaType, e); throw new SLViewerException(5000); } @@ -299,7 +303,7 @@ public class DataObject { } } else { - log.debug("MIME media type '" + mediaType + "' is not a s/valid/SUPPORTED digest input, omitting validation."); + log.debug("MIME media type '{}' is not a s/valid/SUPPORTED digest input, omitting validation.", mediaType); } } @@ -359,12 +363,12 @@ public class DataObject { if (reference != null) { if (reference.getURI() != null && !"".equals(reference.getURI())) { try { - log.info("deriving filename from reference URI " + reference.getURI()); + log.info("Deriving filename from reference URI {}.", reference.getURI()); URI refURI = new URI(reference.getURI()); if (refURI.isOpaque()) { // could check scheme component, but also allow other schemes (e.g. testlocal) - log.trace("opaque reference URI, use scheme-specific part as filename"); + log.trace("Opaque reference URI, use scheme-specific part as filename."); filename = refURI.getSchemeSpecificPart(); if (!hasExtension(filename)) { filename += MimeTypes.getExtension(mimeType); @@ -376,34 +380,34 @@ public class DataObject { } else if ("".equals(refURI.getPath()) && refURI.getFragment() != null && refURI.getFragment().indexOf('(') < 0) { // exclude (schemebased) xpointer expressions - log.trace("fragment (shorthand xpointer) URI, use fragment as filename"); + log.trace("Fragment (shorthand xpointer) URI, use fragment as filename."); filename = refURI.getFragment(); if(!hasExtension(filename)) { filename += MimeTypes.getExtension(mimeType); } } else if (!"".equals(refURI.getPath())) { - log.trace("hierarchical URI with path component, use path as filename"); + log.trace("Hierarchical URI with path component, use path as filename."); File refFile = new File(refURI.getPath()); filename = refFile.getName(); if(!hasExtension(filename)) { filename += MimeTypes.getExtension(mimeType); } } else { - log.debug("failed to derive filename from URI '" + refURI + "', derive filename from reference ID"); + log.debug("Failed to derive filename from URI '{}', derive filename from reference ID.", refURI); filename = reference.getId() + MimeTypes.getExtension(mimeType); } } catch (URISyntaxException ex) { - log.error("failed to derive filename from invalid URI " + ex.getMessage()); + log.error("Failed to derive filename from invalid URI {}.", ex.getMessage()); filename = reference.getId() + MimeTypes.getExtension(mimeType); } } else { - log.debug("same-document URI, derive filename from reference ID"); + log.debug("Same-document URI, derive filename from reference ID."); filename = reference.getId() + MimeTypes.getExtension(mimeType); } } else { - log.error("failed to derive filename, no reference created"); + log.error("Failed to derive filename, no reference created."); } - log.debug("derived filename for reference " + reference.getId() + ": " + filename); + log.debug("Derived filename for reference {}: {}.", reference.getId(), filename); return filename; } @@ -413,30 +417,12 @@ public class DataObject { } private byte[] getTransformsBytes(at.gv.egiz.slbinding.impl.TransformsInfoType ti) { - return ti.getRedirectedStream().toByteArray(); -// byte[] transformsBytes = ti.getRedirectedStream().toByteArray(); -// -// if (transformsBytes == null || transformsBytes.length == 0) { -// return null; -// } -// -// String dsigPrefix = ti.getNamespaceContext().getNamespaceURI("http://www.w3.org/2000/09/xmldsig#"); -// byte[] pre, post; -// if (dsigPrefix == null) { -// log.trace("XMLDSig not declared in outside dsig:Transforms"); -// pre = "".getBytes(); -// post = "".getBytes(); -// } else { -// log.trace("XMLDSig bound to prefix " + dsigPrefix); -// pre = ("").getBytes(); -// post = "".getBytes(); -// } -// -// byte[] workaround = new byte[pre.length + transformsBytes.length + post.length]; -// System.arraycopy(pre, 0, workaround, 0, pre.length); -// System.arraycopy(transformsBytes, 0, workaround, pre.length, transformsBytes.length); -// System.arraycopy(post, 0, workaround, pre.length + transformsBytes.length, post.length); -// return workaround; + ByteArrayOutputStream redirectedStream = ti.getRedirectedStream(); + if (redirectedStream != null) { + return redirectedStream.toByteArray(); + } else { + return null; + } } /** @@ -487,9 +473,8 @@ public class DataObject { // create XMLObject DocumentFragment content = parseDataObject((XMLContentType) dataObject.getXMLContent()); - XMLObject xmlObject = createXMLObject(content); - setXMLObjectAndReferenceXML(xmlObject, transforms); + setXMLObjectAndReferenceXML(createXMLObject(content), transforms); } else if (dataObject.getLocRefContent() != null) { @@ -521,7 +506,7 @@ public class DataObject { // The content of sl:DataObject remains empty // - log.debug("Adding DataObject from reference URI '" + reference + "'."); + log.debug("Adding DataObject from reference URI '{}'.", reference); setEnvelopedDataObject(reference, transforms); @@ -564,13 +549,13 @@ public class DataObject { } // dereference URL - URLDereferencer dereferencer = URLDereferencer.getInstance(); + URLDereferencer dereferencer = ctx.getUrlDereferencer(); StreamData streamData; try { - streamData = dereferencer.dereference(reference, ctx.getDereferencerContext()); + streamData = dereferencer.dereference(reference); } catch (IOException e) { - log.info("Failed to dereference XMLObject from '" + reference + "'.", e); + log.info("Failed to dereference XMLObject from '{}'.", reference, e); throw new SLCommandException(4110); } @@ -587,7 +572,7 @@ public class DataObject { childNode = doc.getDocumentElement(); if (childNode == null) { - log.info("Failed to parse XMLObject from '" + reference + "'."); + log.info("Failed to parse XMLObject from '{}'.", reference); throw new SLCommandException(4111); } @@ -666,12 +651,12 @@ public class DataObject { if (dataObject.getLocRefContent() != null) { String locRef = dataObject.getLocRefContent(); try { - this.reference.setDereferencer(new LocRefDereferencer(ctx.getDereferencerContext(), locRef)); + this.reference.setDereferencer(new LocRefDereferencer(ctx.getUrlDereferencer(), locRef)); } catch (URISyntaxException e) { - log.info("Invalid URI '" + locRef + "' in DataObject.", e); + log.info("Invalid URI '{}' in DataObject.", locRef, e); throw new SLCommandException(4003); } catch (IllegalArgumentException e) { - log.info("LocRef URI of '" + locRef + "' not supported in DataObject. ", e); + log.info("LocRef URI of '{}' not supported in DataObject. ", locRef, e); throw new SLCommandException(4003); } } else if (dataObject.getBase64Content() != null) { @@ -734,7 +719,7 @@ public class DataObject { } if (debugString != null) { - log.debug(debugString); + log.debug(debugString.toString()); } // look for preferred transform @@ -778,7 +763,7 @@ public class DataObject { StringBuilder sb = new StringBuilder(); sb.append("Trying to parse transforms:\n"); sb.append(new String(transforms, Charset.forName("UTF-8"))); - log.trace(sb); + log.trace(sb.toString()); } DOMImplementationLS domImplLS = DOMUtils.getDOMImplementationLS(); @@ -933,8 +918,7 @@ public class DataObject { } catch (MarshalException e) { String mimeType = preferredTransformsInfo.getFinalDataMetaInfo().getMimeType(); - log.info("Failed to unmarshal preferred transformation path (MIME-Type=" - + mimeType + ").", e); + log.info("Failed to unmarshal preferred transformation path (MIME-Type={}).", mimeType, e); } @@ -950,8 +934,7 @@ public class DataObject { } catch (MarshalException e) { String mimeType = transformsInfoType.getFinalDataMetaInfo().getMimeType(); - log.info("Failed to unmarshal transformation path (MIME-Type=" - + mimeType + ").", e); + log.info("Failed to unmarshal transformation path (MIME-Type={}).", mimeType, e); } } @@ -975,7 +958,7 @@ public class DataObject { try { textNode = at.gv.egiz.dom.DOMUtils.createBase64Text(content, ctx.getDocument()); } catch (IOException e) { - log.error(e); + log.error("Failed to create XMLObject.", e); throw new SLRuntimeException(e); } @@ -1170,36 +1153,68 @@ public class DataObject { // content of the redirect stream as the content has already been parsed // and serialized again to the redirect stream. - List inputStreams = new ArrayList(); - try { - // dummy start element - inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); - - // content - inputStreams.add(new ByteArrayInputStream(redirectedStream.toByteArray())); - - // dummy end element - inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - throw new SLRuntimeException(e); - } + DocumentFragment fragment; + if (redirectedStream != null) { - SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreams)); - - // parse DataObject - Document doc = parseDataObject(inputStream, "UTF-8"); + List inputStreams = new ArrayList(); + try { + // dummy start element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); - Element documentElement = doc.getDocumentElement(); - - if (documentElement == null || - !"dummy".equals(documentElement.getLocalName())) { - log.info("Failed to parse DataObject XMLContent."); - throw new SLCommandException(4111); - } + // content + inputStreams.add(new ByteArrayInputStream(redirectedStream.toByteArray())); + + // dummy end element + inputStreams.add(new ByteArrayInputStream("".getBytes("UTF-8"))); + } catch (UnsupportedEncodingException e) { + throw new SLRuntimeException(e); + } + + SequenceInputStream inputStream = new SequenceInputStream(Collections.enumeration(inputStreams)); - DocumentFragment fragment = doc.createDocumentFragment(); - while (documentElement.getFirstChild() != null) { - fragment.appendChild(documentElement.getFirstChild()); + // parse DataObject + Document doc = parseDataObject(inputStream, "UTF-8"); + + Element documentElement = doc.getDocumentElement(); + + if (documentElement == null || + !"dummy".equals(documentElement.getLocalName())) { + log.info("Failed to parse DataObject XMLContent."); + throw new SLCommandException(4111); + } + + fragment = doc.createDocumentFragment(); + while (documentElement.getFirstChild() != null) { + fragment.appendChild(documentElement.getFirstChild()); + } + + } else { + + fragment = ctx.getDocument().createDocumentFragment(); + Marshaller marshaller = SLMarshallerFactory.getInstance().createMarshaller(false); + + JAXBElement element = + new JAXBElement( + new QName("dummy"), + at.buergerkarte.namespaces.securitylayer._1.XMLContentType.class, + xmlContent); + + try { + marshaller.marshal(element, fragment); + } catch (JAXBException e) { + log.info("Failed to marshal DataObject (XMLContent).", e); + throw new SLCommandException(4111); + } + + Node dummy = fragment.getFirstChild(); + if (dummy != null) { + NodeList nodes = dummy.getChildNodes(); + for (int i = 0; i < nodes.getLength(); i++) { + fragment.appendChild(nodes.item(i)); + } + fragment.removeChild(dummy); + } + } // log parsed document @@ -1256,6 +1271,8 @@ public class DataObject { SimpleDOMErrorHandler errorHandler = new SimpleDOMErrorHandler(); domConfig.setParameter("error-handler", errorHandler); domConfig.setParameter("validate", Boolean.FALSE); + domConfig.setParameter("entities", Boolean.TRUE); + Document doc; try { diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java index f5394157..e513738c 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/LocRefDereferencer.java @@ -14,99 +14,96 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; - -import javax.xml.crypto.Data; -import javax.xml.crypto.OctetStreamData; -import javax.xml.crypto.URIDereferencer; -import javax.xml.crypto.URIReference; -import javax.xml.crypto.URIReferenceException; -import javax.xml.crypto.XMLCryptoContext; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import at.gv.egiz.bku.utils.urldereferencer.StreamData; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; - -/** - * An URIDereferencer implementation that dereferences LocRef - * references. - * - * @author mcentner - */ -public class LocRefDereferencer implements URIDereferencer { - - /** - * Logging facility. - */ - private static Log log = LogFactory.getLog(LocRefDereferencer.class); - - /** - * The LocRef-reference to be dereferenced by - * {@link #dereference(URIReference, XMLCryptoContext)}. - */ - protected String locRef; - - /** - * The context to be used for dereferencing. - */ - protected URLDereferencerContext dereferencerContext; - - /** - * Creates a new instance of this LocRefDereferencer with the given - * dereferencerContext and locRef reference. - * - * @param dereferencerContext - * the context to be used for dereferencing - * @param locRef - * the LocRef-reference (must be an absolute URI) - * - * @throws URISyntaxException - * if LocRef is not an absolute URI - */ - public LocRefDereferencer(URLDereferencerContext dereferencerContext, - String locRef) throws URISyntaxException { - - this.dereferencerContext = dereferencerContext; - - URI locRefUri = new URI(locRef); - if (locRefUri.isAbsolute()) { - this.locRef = locRef; - } else { - throw new IllegalArgumentException( - "Parameter 'locRef' must be an absolut URI."); - } - } - - /* - * (non-Javadoc) - * - * @see - * javax.xml.crypto.URIDereferencer#dereference(javax.xml.crypto.URIReference, - * javax.xml.crypto.XMLCryptoContext) - */ - @Override - public Data dereference(URIReference uriReference, XMLCryptoContext context) - throws URIReferenceException { - - URLDereferencer dereferencer = URLDereferencer.getInstance(); - StreamData streamData; - try { - streamData = dereferencer.dereference(locRef, dereferencerContext); - } catch (IOException e) { - log.info("Failed to dereference URI'" + locRef + "'. " + e.getMessage(), - e); - throw new URIReferenceException("Failed to dereference URI '" + locRef - + "'. " + e.getMessage(), e); - } - return new OctetStreamData(streamData.getStream(), locRef, streamData - .getContentType()); - } - -} +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.crypto.Data; +import javax.xml.crypto.OctetStreamData; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReference; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import at.gv.egiz.bku.utils.urldereferencer.StreamData; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; + +/** + * An URIDereferencer implementation that dereferences LocRef + * references. + * + * @author mcentner + */ +public class LocRefDereferencer implements URIDereferencer { + + /** + * Logging facility. + */ + private final Logger log = LoggerFactory.getLogger(LocRefDereferencer.class); + + /** + * The LocRef-reference to be dereferenced by + * {@link #dereference(URIReference, XMLCryptoContext)}. + */ + protected String locRef; + + /** + * The URLDereferencer to be used for dereferencing. + */ + protected URLDereferencer dereferencer; + + /** + * Creates a new instance of this LocRefDereferencer with the given + * dereferencerContext and locRef reference. + * + * @param dereferencer + * the context to be used for dereferencing + * @param locRef + * the LocRef-reference (must be an absolute URI) + * + * @throws URISyntaxException + * if LocRef is not an absolute URI + */ + public LocRefDereferencer(URLDereferencer dereferencer, + String locRef) throws URISyntaxException { + + this.dereferencer = dereferencer; + + URI locRefUri = new URI(locRef); + if (locRefUri.isAbsolute()) { + this.locRef = locRef; + } else { + throw new IllegalArgumentException( + "Parameter 'locRef' must be an absolut URI."); + } + } + + /* + * (non-Javadoc) + * + * @see + * javax.xml.crypto.URIDereferencer#dereference(javax.xml.crypto.URIReference, + * javax.xml.crypto.XMLCryptoContext) + */ + @Override + public Data dereference(URIReference uriReference, XMLCryptoContext context) + throws URIReferenceException { + + StreamData streamData; + try { + streamData = dereferencer.dereference(locRef); + } catch (IOException e) { + log.info("Failed to dereference URI '{}'.", locRef, e); + throw new URIReferenceException("Failed to dereference URI '" + locRef + + "'. " + e.getMessage(), e); + } + return new OctetStreamData(streamData.getStream(), locRef, streamData + .getContentType()); + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java index 25e2d4e5..87a165cf 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALPrivateKey.java @@ -16,7 +16,6 @@ */ package at.gv.egiz.bku.slcommands.impl.xsect; -import at.gv.egiz.stal.HashDataInput; import java.security.PrivateKey; import at.gv.egiz.stal.STAL; @@ -24,7 +23,7 @@ import at.gv.egiz.stal.STAL; import java.util.List; /** - * This class implements a private key used by the {@link STALSignature} class. + * This class implements a private key used by the {@link STALSignatureMethod} class. * * @author mcentner */ diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java deleted file mode 100644 index 9fb9a3f1..00000000 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALProvider.java +++ /dev/null @@ -1,71 +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 at.gv.egiz.bku.slcommands.impl.xsect; - -import iaik.xml.crypto.XmldsigMore; - -import java.security.AccessController; -import java.security.PrivilegedAction; -import java.security.Provider; -import java.security.Signature; -import java.util.HashMap; -import java.util.Map; - -import javax.xml.crypto.dsig.SignatureMethod; - -/** - * A security provider implementation that provides {@link Signature} implementations - * based on STAL. - * - * @author mcentner - */ -public class STALProvider extends Provider { - - private static final long serialVersionUID = 1L; - - private static String IMPL_PACKAGE_NAME = "at.gv.egiz.bku.slcommands.impl.xsect"; - - public STALProvider() { - - super("STAL", 1.0, "Security Token Abstraction Layer Provider"); - - final Map map = new HashMap(); - - // TODO: register further algorithms - map.put("Signature." + SignatureMethod.RSA_SHA1, - IMPL_PACKAGE_NAME + ".STALSignature"); - map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA1, - IMPL_PACKAGE_NAME + ".STALSignature"); - map.put("Signature." + XmldsigMore.SIGNATURE_RSA_SHA256, - IMPL_PACKAGE_NAME + ".STALSignature"); - map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA256, - IMPL_PACKAGE_NAME + ".STALSignature"); - map.put("Signature." + XmldsigMore.SIGNATURE_ECDSA_SHA512, - IMPL_PACKAGE_NAME + ".STALSignature"); - - - AccessController.doPrivileged(new PrivilegedAction() { - @Override - public Void run() { - putAll(map); - return null; - } - }); - - } - -} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java deleted file mode 100644 index dd7c7d8a..00000000 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignature.java +++ /dev/null @@ -1,184 +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 at.gv.egiz.bku.slcommands.impl.xsect; - -import at.gv.egiz.bku.slcommands.impl.DataObjectHashDataInput; -import at.gv.egiz.bku.slexceptions.SLViewerException; - -import java.io.ByteArrayOutputStream; -import java.security.InvalidKeyException; -import java.security.InvalidParameterException; -import java.security.PrivateKey; -import java.security.PublicKey; -import java.security.SignatureException; -import java.security.SignatureSpi; -import java.util.Collections; -import java.util.List; - -import at.gv.egiz.stal.ErrorResponse; -import at.gv.egiz.stal.HashDataInput; -import at.gv.egiz.stal.STAL; -import at.gv.egiz.stal.STALRequest; -import at.gv.egiz.stal.STALResponse; -import at.gv.egiz.stal.SignRequest; -import at.gv.egiz.stal.SignResponse; -//import at.gv.egiz.stal.HashDataInputCallback; -import java.util.ArrayList; - -/** - * A signature service provider implementation that uses STAL to sign. - * - * @author mcentner - */ -public class STALSignature extends SignatureSpi { - -// private static final Log log = LogFactory.getLog(STALSignature.class); - - /** - * The private key. - */ - protected STALPrivateKey privateKey; - - /** - * The to-be signed data. - */ - protected ByteArrayOutputStream data = new ByteArrayOutputStream(); - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineGetParameter(java.lang.String) - */ - @Override - protected Object engineGetParameter(String param) - throws InvalidParameterException { - throw new InvalidParameterException(); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineInitSign(java.security.PrivateKey) - */ - @Override - protected void engineInitSign(PrivateKey privateKey) - throws InvalidKeyException { - - if (!(privateKey instanceof STALPrivateKey)) { - throw new InvalidKeyException("STALSignature supports STALKeys only."); - } - - this.privateKey = (STALPrivateKey) privateKey; - - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineInitVerify(java.security.PublicKey) - */ - @Override - protected void engineInitVerify(PublicKey publicKey) - throws InvalidKeyException { - - throw new UnsupportedOperationException("STALSignature does not support signature verification."); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineSetParameter(java.lang.String, java.lang.Object) - */ - @Override - protected void engineSetParameter(String param, Object value) - throws InvalidParameterException { - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineSign() - */ - @Override - protected byte[] engineSign() throws SignatureException { - - STAL stal = privateKey.getStal(); - - if (stal == null) { - throw new SignatureException("STALSignature requires the STALPrivateKey " + - "to provide a STAL implementation reference."); - } - - String keyboxIdentifier = privateKey.getKeyboxIdentifier(); - - if (keyboxIdentifier == null) { - throw new SignatureException("STALSignature requires the STALPrivateKey " + - "to provide a KeyboxIdentifier."); - } - - // get hashDataInputs (DigestInputStreams) once slcommands.impl.xsect.Signature::sign() was called - List dataObjects = privateKey.getDataObjects(); -// log.debug("got " + dataObjects.size() + " DataObjects, passing HashDataInputs to STAL SignRequest"); - - List hashDataInputs = new ArrayList(); - for (DataObject dataObject : dataObjects) { - try { - dataObject.validateHashDataInput(); - } catch (SLViewerException e) { - throw new STALSignatureException(e); - } - hashDataInputs.add(new DataObjectHashDataInput(dataObject)); - } - - SignRequest signRequest = new SignRequest(); - signRequest.setKeyIdentifier(keyboxIdentifier); - signRequest.setSignedInfo(data.toByteArray()); - signRequest.setHashDataInput(hashDataInputs); - - List responses = stal.handleRequest(Collections.singletonList((STALRequest) signRequest)); - - if (responses == null || responses.size() != 1) { - throw new SignatureException("Failed to access STAL."); - } - - STALResponse response = responses.get(0); - if (response instanceof SignResponse) { - return ((SignResponse) response).getSignatureValue(); - } else if (response instanceof ErrorResponse) { - throw new STALSignatureException(((ErrorResponse) response).getErrorCode()); - } else { - throw new SignatureException("Failed to access STAL."); - } - - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineUpdate(byte) - */ - @Override - protected void engineUpdate(byte b) throws SignatureException { - data.write(b); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineUpdate(byte[], int, int) - */ - @Override - protected void engineUpdate(byte[] b, int off, int len) - throws SignatureException { - data.write(b, off, len); - } - - /* (non-Javadoc) - * @see java.security.SignatureSpi#engineVerify(byte[]) - */ - @Override - protected boolean engineVerify(byte[] sigBytes) throws SignatureException { - throw new UnsupportedOperationException("STALSignature des not support signature verification."); - } - -} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java index 4e86b07c..b727600f 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureException.java @@ -19,7 +19,7 @@ package at.gv.egiz.bku.slcommands.impl.xsect; import java.security.SignatureException; /** - * A SignatureException thrown by the {@link STALSignature}. + * A SignatureException thrown by the {@link STALSignatureMethod}. * * @author mcentner */ diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureMethod.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureMethod.java new file mode 100644 index 00000000..a9bb8e04 --- /dev/null +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/STALSignatureMethod.java @@ -0,0 +1,127 @@ +/* +* Copyright 2009 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 at.gv.egiz.bku.slcommands.impl.xsect; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.security.InvalidAlgorithmParameterException; +import java.security.Key; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.crypto.XMLCryptoContext; +import javax.xml.crypto.dsig.XMLSignatureException; +import javax.xml.crypto.dsig.spec.SignatureMethodParameterSpec; + +import at.gv.egiz.bku.slcommands.impl.DataObjectHashDataInput; +import at.gv.egiz.bku.slexceptions.SLViewerException; +import at.gv.egiz.bku.utils.StreamUtil; +import at.gv.egiz.stal.ErrorResponse; +import at.gv.egiz.stal.HashDataInput; +import at.gv.egiz.stal.STAL; +import at.gv.egiz.stal.STALRequest; +import at.gv.egiz.stal.STALResponse; +import at.gv.egiz.stal.SignRequest; +import at.gv.egiz.stal.SignResponse; + +import iaik.xml.crypto.dsig.AbstractSignatureMethodImpl; + +public class STALSignatureMethod extends AbstractSignatureMethodImpl { + + /** + * Creates a new instance of this STALSignatureMethod + * with the given algorithm and params. + * + * @param algorithm the algorithm URI + * @param params optional algorithm parameters + * @throws InvalidAlgorithmParameterException if the specified parameters + * are inappropriate for the requested algorithm + * @throws NoSuchAlgorithmException if an implementation of the specified + * algorithm cannot be found + * @throws NullPointerException if algorithm is null + */ + public STALSignatureMethod(String algorithm, + SignatureMethodParameterSpec params) + throws InvalidAlgorithmParameterException, NoSuchAlgorithmException { + super(algorithm, params); + } + + @Override + public byte[] calculateSignatureValue(XMLCryptoContext context, Key key, InputStream message) + throws XMLSignatureException, IOException { + + if (!(key instanceof STALPrivateKey)) { + throw new XMLSignatureException("STALSignatureMethod expects STALPrivateKey."); + } + + STAL stal = ((STALPrivateKey) key).getStal(); + String keyboxIdentifier = ((STALPrivateKey) key).getKeyboxIdentifier(); + List dataObjects = ((STALPrivateKey) key).getDataObjects(); + + List hashDataInputs = new ArrayList(); + for (DataObject dataObject : dataObjects) { + try { + dataObject.validateHashDataInput(); + } catch (SLViewerException e) { + throw new XMLSignatureException(e); + } + hashDataInputs.add(new DataObjectHashDataInput(dataObject)); + } + + ByteArrayOutputStream m = new ByteArrayOutputStream(); + StreamUtil.copyStream(message, m); + + SignRequest signRequest = new SignRequest(); + signRequest.setKeyIdentifier(keyboxIdentifier); + signRequest.setSignedInfo(m.toByteArray()); + signRequest.setHashDataInput(hashDataInputs); + + List responses = + stal.handleRequest(Collections.singletonList((STALRequest) signRequest)); + + if (responses == null || responses.size() != 1) { + throw new XMLSignatureException("Failed to access STAL."); + } + + STALResponse response = responses.get(0); + if (response instanceof SignResponse) { + return ((SignResponse) response).getSignatureValue(); + } else if (response instanceof ErrorResponse) { + STALSignatureException se = new STALSignatureException(((ErrorResponse) response).getErrorCode()); + throw new XMLSignatureException(se); + } else { + throw new XMLSignatureException("Failed to access STAL."); + } + + } + + @Override + public boolean validateSignatureValue(XMLCryptoContext context, Key key, byte[] value, + InputStream message) throws XMLSignatureException, IOException { + throw new XMLSignatureException("The STALSignatureMethod does not support validation."); + } + + @Override + protected Class getParameterSpecClass() { + return null; + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java index 3cebb6a3..b4ce0e79 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/Signature.java @@ -51,8 +51,8 @@ import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory; import javax.xml.crypto.dsig.keyinfo.X509Data; import javax.xml.stream.XMLStreamException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.etsi.uri._01903.v1_1.DataObjectFormatType; import org.etsi.uri._01903.v1_1.QualifyingPropertiesType; import org.w3c.dom.DOMConfiguration; @@ -82,7 +82,6 @@ import at.gv.egiz.bku.slexceptions.SLViewerException; import at.gv.egiz.bku.utils.HexDump; import at.gv.egiz.bku.utils.urldereferencer.StreamData; import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; import at.gv.egiz.dom.DOMUtils; import at.gv.egiz.slbinding.impl.XMLContentType; import at.gv.egiz.stal.STAL; @@ -101,7 +100,7 @@ public class Signature { /** * Logging facility. */ - private static Log log = LogFactory.getLog(Signature.class); + private final Logger log = LoggerFactory.getLogger(Signature.class); /** * The DOM implementation used. @@ -151,8 +150,9 @@ public class Signature { /** * Creates a new SLXMLSignature instance. + * @param urlDereferencer TODO */ - public Signature(URLDereferencerContext dereferencerContext, + public Signature(URLDereferencer urlDereferencer, IdValueFactory idValueFactory, AlgorithmMethodFactory algorithmMethodFactory) { @@ -162,7 +162,7 @@ public class Signature { ctx.setSignatureFactory(XMLSignatureFactory.getInstance()); - ctx.setDereferencerContext(dereferencerContext); + ctx.setUrlDereferencer(urlDereferencer); ctx.setIdValueFactory(idValueFactory); ctx.setAlgorithmMethodFactory(algorithmMethodFactory); @@ -408,7 +408,7 @@ public class Signature { signContext.putNamespacePrefix(XMLSignature.XMLNS,XMLDSIG_PREFIX); - signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getDereferencerContext())); + signContext.setURIDereferencer(new URIDereferncerAdapter(ctx.getUrlDereferencer())); try { xmlSignature.sign(signContext); @@ -455,7 +455,7 @@ public class Signature { sb.append(HexDump.hexDump(digestInputStream)); } } catch (IOException e) { - log.error(e); + log.error("Failed to log DigestInput.", e); } log.trace(sb.toString()); } else { @@ -478,7 +478,7 @@ public class Signature { sb.append(new String(b, 0, l)); } } catch (IOException e) { - log.error(e); + log.error("Failed to log DigestInput.", e); } log.trace(sb.toString()); } else { @@ -735,7 +735,7 @@ public class Signature { LSInput input; try { if (signatureEnvironment.getReference() != null) { - log.debug("SignatureEnvironment contains Reference " + signatureEnvironment.getReference() + "."); + log.debug("SignatureEnvironment contains Reference '{}'.", signatureEnvironment.getReference()); input = createLSInput(signatureEnvironment.getReference()); } else if (signatureEnvironment.getBase64Content() != null) { log.debug("SignatureEnvironment contains Base64Content."); @@ -784,11 +784,12 @@ public class Signature { if (log.isInfoEnabled()) { List errorMessages = errorHandler.getErrorMessages(); StringBuffer sb = new StringBuffer(); + sb.append("XML document in which the signature is to be integrated cannot be parsed."); for (String errorMessage : errorMessages) { sb.append(" "); sb.append(errorMessage); } - log.info("XML document in which the signature is to be integrated cannot be parsed." + sb.toString()); + log.info(sb.toString()); } throw new SLCommandException(4101); } @@ -826,8 +827,8 @@ public class Signature { */ private LSInput createLSInput(String reference) throws IOException { - URLDereferencer urlDereferencer = URLDereferencer.getInstance(); - StreamData streamData = urlDereferencer.dereference(reference, ctx.getDereferencerContext()); + URLDereferencer urlDereferencer = ctx.getUrlDereferencer(); + StreamData streamData = urlDereferencer.dereference(reference); String contentType = streamData.getContentType(); String charset = HttpUtil.getCharset(contentType, true); @@ -835,7 +836,7 @@ public class Signature { try { streamReader = new InputStreamReader(streamData.getStream(), charset); } catch (UnsupportedEncodingException e) { - log.info("Charset " + charset + " not supported. Using default."); + log.info("Charset {} not supported. Using default.", charset); streamReader = new InputStreamReader(streamData.getStream()); } @@ -942,7 +943,7 @@ public class Signature { if (systemId != null) { - log.debug("Resolve resource '" + systemId + "'."); + log.debug("Resolve resource '{}'.", systemId); for (DataObjectAssociationType supplement : supplements) { @@ -954,23 +955,23 @@ public class Signature { try { if (content.getLocRefContent() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with LocRefContent."); + log.trace("Resolved resource '{}' to supplement with LocRefContent.", reference); return createLSInput(content.getLocRefContent()); } else if (content.getBase64Content() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with Base64Content."); + log.trace("Resolved resource '{}' to supplement with Base64Content.", reference); return createLSInput(content.getBase64Content()); } else if (content.getXMLContent() != null) { - log.trace("Resolved resource '" + reference + "' to supplement with XMLContent."); + log.trace("Resolved resource '{}' to supplement with XMLContent.", reference); return createLSInput((XMLContentType) content.getXMLContent()); } else { return null; } } catch (IOException e) { - log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + log.info("Failed to resolve resource '{}' to supplement.", systemId, e); error = e; return null; } catch (XMLStreamException e) { - log.info("Failed to resolve resource '" + systemId + "' to supplement.", e); + log.info("Failed to resolve resource '{}' to supplement.", systemId, e); error = e; return null; } @@ -981,7 +982,7 @@ public class Signature { } - log.info("Failed to resolve resource '" + systemId + "' to supplement. No such supplement."); + log.info("Failed to resolve resource '{}' to supplement. No such supplement.", systemId); } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java index 0925f2fd..48c82bd5 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureContext.java @@ -16,12 +16,12 @@ */ package at.gv.egiz.bku.slcommands.impl.xsect; -import javax.xml.crypto.dsig.DigestMethod; +import javax.xml.crypto.AlgorithmMethod; import javax.xml.crypto.dsig.XMLSignatureFactory; import org.w3c.dom.Document; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; /** * An instance of this class carries context information for a XML-Signature @@ -45,16 +45,16 @@ public class SignatureContext { * The XMLSignatureFactory to create XML signature objects. */ private XMLSignatureFactory signatureFactory; + + /** + * The URLDereferencer to dereference URLs with. + */ + private URLDereferencer urlDereferencer; /** - * The URLDereferencerContext for dereferencing URLs. + * The AlgorithmMethodFactory to create {@link AlgorithmMethod} objects. */ - private URLDereferencerContext dereferencerContext; - - /** - * The DigestMethodFactory to create {@link DigestMethod} objects. - */ - private AlgorithmMethodFactory digestMethodFactory; + private AlgorithmMethodFactory algorithmMethodFactory; /** * @return the document @@ -98,32 +98,32 @@ public class SignatureContext { this.signatureFactory = signatureFactory; } - /** - * @return the dereferencerContext - */ - public URLDereferencerContext getDereferencerContext() { - return dereferencerContext; - } - - /** - * @param dereferencerContext the dereferencerContext to set - */ - public void setDereferencerContext(URLDereferencerContext dereferencerContext) { - this.dereferencerContext = dereferencerContext; - } - /** * @return the digestMethodFactory */ public AlgorithmMethodFactory getAlgorithmMethodFactory() { - return digestMethodFactory; + return algorithmMethodFactory; } /** * @param digestMethodFactory the digestMethodFactory to set */ public void setAlgorithmMethodFactory(AlgorithmMethodFactory digestMethodFactory) { - this.digestMethodFactory = digestMethodFactory; + this.algorithmMethodFactory = digestMethodFactory; + } + + /** + * @return the urlDereferencer + */ + public URLDereferencer getUrlDereferencer() { + return urlDereferencer; + } + + /** + * @param urlDereferencer the urlDereferencer to set + */ + public void setUrlDereferencer(URLDereferencer urlDereferencer) { + this.urlDereferencer = urlDereferencer; } } diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java index ebe50b3f..26a4aa4e 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/SignatureLocation.java @@ -14,212 +14,212 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package at.gv.egiz.bku.slcommands.impl.xsect; - -import java.util.Iterator; - -import javax.xml.XMLConstants; -import javax.xml.namespace.NamespaceContext; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathExpression; -import javax.xml.xpath.XPathExpressionException; -import javax.xml.xpath.XPathFactory; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.w3c.dom.Node; - -import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; -import at.gv.egiz.bku.slexceptions.SLCommandException; -import at.gv.egiz.slbinding.impl.SignatureLocationType; - -/** - * This class implements the SignatureLocation of an XML-Signature - * to be created by the security layer command CreateXMLSignature. - * - * @author mcentner - */ -public class SignatureLocation { - - /** - * Logging facility. - */ - private static Log log = LogFactory.getLog(SignatureLocation.class); - - /** - * The SignatureContext for the XML signature - */ - private SignatureContext ctx; - - /** - * The parent node for the XML signature. - */ - private Node parent; - - /** - * The next sibling node for the XML signature. - */ - private Node nextSibling; - - /** - * Creates a new SignatureLocation with the given signatureContext - * - * @param signatureContext the context for the XML signature creation - */ - public SignatureLocation(SignatureContext signatureContext) { - this.ctx = signatureContext; - } - - /** - * @return the parent node for the XML signature - */ - public Node getParent() { - return parent; - } - - /** - * @param parent the parent for the XML signature - */ - public void setParent(Node parent) { - this.parent = parent; - } - - /** - * @return the next sibling node for the XML signature - */ - public Node getNextSibling() { - return nextSibling; - } - - /** - * @param nextSibling the next sibling node for the XML signature - */ - public void setNextSibling(Node nextSibling) { - this.nextSibling = nextSibling; - } - - /** - * Configures this SignatureLocation with the information provided by the - * given SignatureInfo element. - * - * @param signatureInfo - * the SignatureInfo element - * - * @throws SLCommandException - * if configuring this SignatureLocation with given - * signatureInfofails - */ - public void setSignatureInfo(SignatureInfoCreationType signatureInfo) - throws SLCommandException { - - // evaluate signature location XPath ... - SignatureLocationType signatureLocation = (SignatureLocationType) signatureInfo - .getSignatureLocation(); - - NamespaceContext namespaceContext = new MOAIDWorkaroundNamespaceContext( - signatureLocation.getNamespaceContext()); - - parent = evaluateSignatureLocation(signatureInfo.getSignatureLocation() - .getValue(), namespaceContext, ctx.getDocument().getDocumentElement()); - - // ... and index - nextSibling = findNextSibling(parent, signatureInfo.getSignatureLocation() - .getIndex().intValue()); - - } - - /** - * Evaluates the given xpath with the document element as context node - * and returns the resulting node. - * - * @param xpath the XPath expression - * @param nsContext the namespace context of the XPath expression - * @param contextNode the context node for the XPath evaluation - * - * @return the result of evaluating the XPath expression - * - * @throws SLCommandException - */ - private Node evaluateSignatureLocation(String xpath, NamespaceContext nsContext, Node contextNode) throws SLCommandException { - - Node node = null; - try { - XPathFactory xpathFactory = XPathFactory.newInstance(); - XPath xPath = xpathFactory.newXPath(); - xPath.setNamespaceContext(nsContext); - XPathExpression xpathExpr = xPath.compile(xpath); - node = (Node) xpathExpr.evaluate(contextNode, XPathConstants.NODE); - } catch (XPathExpressionException e) { - log.info("Failed to evaluate SignatureLocation XPath expression '" + xpath + "' on context node.", e); - throw new SLCommandException(4102); - } - - if (node == null) { - log.info("Failed to evaluate SignatureLocation XPath expression '" + xpath + "'. Result is empty."); - throw new SLCommandException(4102); - } - - return node; - - } - - /** - * Finds the next sibling node of the parent's n-th child node - * or null if there is no next sibling. - * - * @param parent the parent node - * @param n the index of the child node - * - * @return the next sibling node of the node specified by parent and index n, - * or null if there is no next sibling node. - * - * @throws SLCommandException if the n-th child of parent does not exist - */ - private Node findNextSibling(Node parent, int n) throws SLCommandException { - return parent.getChildNodes().item(n); - } - - /** - * Workaround for a missing namespace prefix declaration in MOA-ID. - * - * @author mcentner - */ - private class MOAIDWorkaroundNamespaceContext implements NamespaceContext { - - private NamespaceContext namespaceContext; - - public MOAIDWorkaroundNamespaceContext(NamespaceContext namespaceContext) { - super(); - this.namespaceContext = namespaceContext; - } - - @Override - public String getNamespaceURI(String prefix) { - - String namespaceURI = namespaceContext.getNamespaceURI(prefix); - - if ((namespaceURI == null || XMLConstants.NULL_NS_URI.equals(namespaceURI)) && "saml".equals(prefix)) { - namespaceURI = "urn:oasis:names:tc:SAML:1.0:assertion"; - log.debug("Namespace prefix '" + prefix + "' resolved to '" + namespaceURI + "' (MOA-ID Workaround)."); - } else { - log.trace("Namespace prefix '" + prefix + "' resolved to '" + namespaceURI + "'."); - } - - return namespaceURI; - } - - @Override - public String getPrefix(String namespaceURI) { - return namespaceContext.getPrefix(namespaceURI); - } - - @SuppressWarnings("unchecked") - @Override - public Iterator getPrefixes(String namespaceURI) { - return namespaceContext.getPrefixes(namespaceURI); - } - - } - -} +package at.gv.egiz.bku.slcommands.impl.xsect; + +import java.util.Iterator; + +import javax.xml.XMLConstants; +import javax.xml.namespace.NamespaceContext; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.w3c.dom.Node; + +import at.buergerkarte.namespaces.securitylayer._1.SignatureInfoCreationType; +import at.gv.egiz.bku.slexceptions.SLCommandException; +import at.gv.egiz.slbinding.impl.SignatureLocationType; + +/** + * This class implements the SignatureLocation of an XML-Signature + * to be created by the security layer command CreateXMLSignature. + * + * @author mcentner + */ +public class SignatureLocation { + + /** + * Logging facility. + */ + private final Logger log = LoggerFactory.getLogger(SignatureLocation.class); + + /** + * The SignatureContext for the XML signature + */ + private SignatureContext ctx; + + /** + * The parent node for the XML signature. + */ + private Node parent; + + /** + * The next sibling node for the XML signature. + */ + private Node nextSibling; + + /** + * Creates a new SignatureLocation with the given signatureContext + * + * @param signatureContext the context for the XML signature creation + */ + public SignatureLocation(SignatureContext signatureContext) { + this.ctx = signatureContext; + } + + /** + * @return the parent node for the XML signature + */ + public Node getParent() { + return parent; + } + + /** + * @param parent the parent for the XML signature + */ + public void setParent(Node parent) { + this.parent = parent; + } + + /** + * @return the next sibling node for the XML signature + */ + public Node getNextSibling() { + return nextSibling; + } + + /** + * @param nextSibling the next sibling node for the XML signature + */ + public void setNextSibling(Node nextSibling) { + this.nextSibling = nextSibling; + } + + /** + * Configures this SignatureLocation with the information provided by the + * given SignatureInfo element. + * + * @param signatureInfo + * the SignatureInfo element + * + * @throws SLCommandException + * if configuring this SignatureLocation with given + * signatureInfofails + */ + public void setSignatureInfo(SignatureInfoCreationType signatureInfo) + throws SLCommandException { + + // evaluate signature location XPath ... + SignatureLocationType signatureLocation = (SignatureLocationType) signatureInfo + .getSignatureLocation(); + + NamespaceContext namespaceContext = new MOAIDWorkaroundNamespaceContext( + signatureLocation.getNamespaceContext()); + + parent = evaluateSignatureLocation(signatureInfo.getSignatureLocation() + .getValue(), namespaceContext, ctx.getDocument().getDocumentElement()); + + // ... and index + nextSibling = findNextSibling(parent, signatureInfo.getSignatureLocation() + .getIndex().intValue()); + + } + + /** + * Evaluates the given xpath with the document element as context node + * and returns the resulting node. + * + * @param xpath the XPath expression + * @param nsContext the namespace context of the XPath expression + * @param contextNode the context node for the XPath evaluation + * + * @return the result of evaluating the XPath expression + * + * @throws SLCommandException + */ + private Node evaluateSignatureLocation(String xpath, NamespaceContext nsContext, Node contextNode) throws SLCommandException { + + Node node = null; + try { + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPath xPath = xpathFactory.newXPath(); + xPath.setNamespaceContext(nsContext); + XPathExpression xpathExpr = xPath.compile(xpath); + node = (Node) xpathExpr.evaluate(contextNode, XPathConstants.NODE); + } catch (XPathExpressionException e) { + log.info("Failed to evaluate SignatureLocation XPath expression '{}' on context node.", xpath, e); + throw new SLCommandException(4102); + } + + if (node == null) { + log.info("Failed to evaluate SignatureLocation XPath expression '{}'. Result is empty.", xpath); + throw new SLCommandException(4102); + } + + return node; + + } + + /** + * Finds the next sibling node of the parent's n-th child node + * or null if there is no next sibling. + * + * @param parent the parent node + * @param n the index of the child node + * + * @return the next sibling node of the node specified by parent and index n, + * or null if there is no next sibling node. + * + * @throws SLCommandException if the n-th child of parent does not exist + */ + private Node findNextSibling(Node parent, int n) throws SLCommandException { + return parent.getChildNodes().item(n); + } + + /** + * Workaround for a missing namespace prefix declaration in MOA-ID. + * + * @author mcentner + */ + private class MOAIDWorkaroundNamespaceContext implements NamespaceContext { + + private NamespaceContext namespaceContext; + + public MOAIDWorkaroundNamespaceContext(NamespaceContext namespaceContext) { + super(); + this.namespaceContext = namespaceContext; + } + + @Override + public String getNamespaceURI(String prefix) { + + String namespaceURI = namespaceContext.getNamespaceURI(prefix); + + if ((namespaceURI == null || XMLConstants.NULL_NS_URI.equals(namespaceURI)) && "saml".equals(prefix)) { + namespaceURI = "urn:oasis:names:tc:SAML:1.0:assertion"; + log.debug("Namespace prefix '{}' resolved to '{}' (MOA-ID Workaround).", prefix, namespaceURI); + } else { + log.trace("Namespace prefix '{}' resolved to '{}'.", prefix, namespaceURI); + } + + return namespaceURI; + } + + @Override + public String getPrefix(String namespaceURI) { + return namespaceContext.getPrefix(namespaceURI); + } + + @SuppressWarnings("unchecked") + @Override + public Iterator getPrefixes(String namespaceURI) { + return namespaceContext.getPrefixes(namespaceURI); + } + + } + +} diff --git a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java index c94937be..5ae728b3 100644 --- a/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java +++ b/bkucommon/src/main/java/at/gv/egiz/bku/slcommands/impl/xsect/URIDereferncerAdapter.java @@ -30,8 +30,7 @@ import javax.xml.crypto.URIReferenceException; import javax.xml.crypto.XMLCryptoContext; import at.gv.egiz.bku.utils.urldereferencer.StreamData; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; -import at.gv.egiz.bku.utils.urldereferencer.URLDereferencerContext; +import at.gv.egiz.bku.utils.urldereferencer.URLDereferencer; /** * An URIDereferencer implementation that uses an {@link URLDereferencer} to @@ -44,17 +43,17 @@ public class URIDereferncerAdapter implements URIDereferencer { /** * The context for dereferencing. */ - protected URLDereferencerContext urlDereferencerContext; + protected URLDereferencer dereferencer; /** * Creates a new URIDereferencerAdapter instance with the given * urlDereferencerContext. * - * @param urlDereferencerContext the context to be used for dereferencing + * @param urlDereferencer the context to be used for dereferencing */ - public URIDereferncerAdapter(URLDereferencerContext urlDereferencerContext) { + public URIDereferncerAdapter(URLDereferencer urlDereferencer) { super(); - this.urlDereferencerContext = urlDereferencerContext; + this.dereferencer = urlDereferencer; } /* (non-Javadoc) @@ -78,10 +77,9 @@ public class URIDereferncerAdapter implements URIDereferencer { if (uri.isAbsolute()) { - URLDereferencer dereferencer = URLDereferencer.getInstance(); StreamData streamData; try { - streamData = dereferencer.dereference(uriString, urlDereferencerContext); + streamData = dereferencer.dereference(uriString); } catch (IOException e) { throw new URIReferenceException(e.getMessage(), e); } -- cgit v1.2.3