aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/at/knowcenter/wag/egov/egiz/sig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/java/at/knowcenter/wag/egov/egiz/sig')
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/Connector.java59
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java326
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorInformation.java89
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/DummyLDAPAPI.java70
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java117
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureBlock.java306
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureEntry.java155
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureFieldDefinition.java80
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java1499
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureResponse.java470
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureSeparator.java139
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypeDefinition.java423
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypes.java462
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/X509Cert.java462
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/A1Connector.java55
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java813
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUPostConnection.java95
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/ConnectorConfigurationKeys.java35
-rw-r--r--src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/MOAConnector.java880
19 files changed, 6535 insertions, 0 deletions
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/Connector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/Connector.java
new file mode 100644
index 0000000..a3d8128
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/Connector.java
@@ -0,0 +1,59 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: Connector.java,v 1.3 2006/10/11 07:54:03 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+
+/**
+ * The basic interface for all connectors.
+ *
+ * @author wprinz
+ */
+public interface Connector
+{
+
+ /**
+ * Performs a sign.
+ *
+ * @param sig_type
+ * The signature type/profile.
+ * @param user_name
+ * The user name for user logging.
+ * @param text_to_sign
+ * The text to be signed.
+ * @return Returns the signed SignatureObject.
+ * @throws SignatureException
+ * F.e.
+ */
+ public SignatureObject doSign(String sig_type, String user_name,
+ String text_to_sign) throws SignatureException;
+
+ /**
+ * Performs a verify.
+ *
+ * @param signed_text
+ * The signed text to be verified.
+ * @param sig_obj
+ * The Signature object.
+ * @return Returns the SignatureResponse.
+ * @throws SignatureException
+ * F.e.
+ */
+ public SignatureResponse doVerify(String signed_text, SignatureObject sig_obj) throws SignatureException;
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java
new file mode 100644
index 0000000..f24f3a5
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorFactory.java
@@ -0,0 +1,326 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: ConnectorFactory.java,v 1.4 2006/10/31 08:18:12 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.lang.reflect.Field;
+
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.ConnectorFactoryException;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.sig.connectors.A1Connector;
+import at.knowcenter.wag.egov.egiz.sig.connectors.BKUConnector;
+import at.knowcenter.wag.egov.egiz.sig.connectors.ConnectorConfigurationKeys;
+import at.knowcenter.wag.egov.egiz.sig.connectors.MOAConnector;
+
+/**
+ * This is a factory for creating the appropriate connector according to the
+ * connector identifier.
+ *
+ * @see at.knowcenter.wag.egov.egiz.sig.ConnectorInformation
+ * @author wprinz
+ */
+public abstract class ConnectorFactory
+{
+ /**
+ * The name of the field that holds the Connector implementation's unique
+ * identifier.
+ *
+ * <p>
+ * This must be a public static final String on the Connector implementation
+ * class.
+ * </p>
+ */
+ protected static final String CONNECTOR_INFORMATION_FIELD_NAME = "CONNECTOR_INFORMATION";
+
+ /**
+ * The list of available Connector implementations.
+ *
+ * <p>
+ * Note that this could also be generated dynamically from a config file,
+ * preferably enveloped by a Singleton.
+ * </p>
+ */
+ protected static Class[] AVAILABLE_CONNECTORS = { MOAConnector.class,
+ BKUConnector.class, A1Connector.class };
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(ConnectorFactory.class);
+
+ /**
+ * Retrieves the ConnectorInformation from the connector Class.
+ *
+ * @param connector_class
+ * The connector Class.
+ * @return Returns the ConnectorInformation.
+ * @throws IllegalArgumentException
+ * F.e.
+ * @throws IllegalAccessException
+ * F.e.
+ * @throws SecurityException
+ * F.e.
+ * @throws NoSuchFieldException
+ * F.e.
+ */
+ protected static ConnectorInformation getConnectorInformationFromClass(
+ Class connector_class) throws IllegalArgumentException, IllegalAccessException, SecurityException, NoSuchFieldException
+ {
+ Field type_field = connector_class.getField(CONNECTOR_INFORMATION_FIELD_NAME);
+ ConnectorInformation connector_information = (ConnectorInformation) type_field.get(null);
+ return connector_information;
+ }
+
+ /**
+ * Gathers the ConnectorInformation objects of all registered connectors.
+ *
+ * <p>
+ * This is used by the user interface to provide a list of all available
+ * connectors.
+ * </p>
+ *
+ * @return Returns the ConnectorInformation objects.
+ * @throws ConnectorFactoryException
+ * F.e.
+ */
+ public static ConnectorInformation[] getConnectorInformationArray() throws ConnectorFactoryException
+ {
+ ConnectorInformation[] coninf = new ConnectorInformation[AVAILABLE_CONNECTORS.length];
+
+ for (int i = 0; i < coninf.length; i++)
+ {
+ try
+ {
+ coninf[i] = getConnectorInformationFromClass(AVAILABLE_CONNECTORS[i]);
+ }
+ catch (Exception e)
+ {
+ throw new ConnectorFactoryException(e);
+ }
+ }
+
+ return coninf;
+ }
+
+ /**
+ * Retrieves the connector Class belonging to the connector id.
+ *
+ * @param connector_identifier
+ * The connector id.
+ * @return Returns the corresponding connector class.
+ * @throws ConnectorFactoryException
+ * Thrown, if the id is invalid.
+ */
+ protected static Class getConnectorClass(String connector_identifier) throws ConnectorFactoryException
+ {
+ ConnectorInformation[] conids = getConnectorInformationArray();
+ for (int i = 0; i < conids.length; i++)
+ {
+ String connector_id = conids[i].getIdentifier();
+
+ if (connector_id.equals(connector_identifier))
+ {
+ Class conn_class = AVAILABLE_CONNECTORS[i];
+
+ return conn_class;
+ }
+ }
+
+ throw new ConnectorFactoryException("The connector '" + connector_identifier + "' couldn't be found in the list of available connectors.");
+ }
+
+ /**
+ * Creates a new connector given by the connector_identifier.
+ *
+ * @param connector_identifier
+ * The connector identifier of the new connector.
+ * @return Returns the new connector.
+ * @throws ConnectorFactoryException
+ * F.e.
+ */
+ public static Connector createConnector(String connector_identifier) throws ConnectorFactoryException
+ {
+
+ Class conn_class = getConnectorClass(connector_identifier);
+
+ try
+ {
+ Connector connector_obj = (Connector) conn_class.newInstance();
+ return connector_obj;
+ }
+ catch (Exception e)
+ {
+ throw new ConnectorFactoryException(e);
+ }
+ }
+
+ /**
+ * Tells, if the given connector identifier is valid.
+ *
+ * @param connector_identifier
+ * The connector identifier.
+ * @return Returns true, if the identifier is valid, false otherwise.
+ * @throws ConnectorFactoryException
+ * F.e.
+ */
+ public static boolean isValidConnectorIdentifier(String connector_identifier) throws ConnectorFactoryException
+ {
+ ConnectorInformation[] conids = getConnectorInformationArray();
+ for (int i = 0; i < conids.length; i++)
+ {
+ if (conids[i].getIdentifier().equals(connector_identifier))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Retrieves the availability of the connector from the flags specified in the
+ * config file.
+ *
+ * @param connector_identifier
+ * The connector.
+ * @param availability_key
+ * The key of the availability flag to be retrieved.
+ * @param default_value
+ * The default value to be used if the flag is not set in the config
+ * file.
+ * @return Returns true, if the flag was set to true, false, if the flag was
+ * set otherwise, or the default_value if the flag wasn't set at all.
+ * @throws ConnectorFactoryException
+ * Thrown, if the connector is invalid.
+ */
+ protected static boolean getAvailabilityUsingDefault(String connector_identifier,
+ String availability_key, boolean default_value) throws ConnectorFactoryException
+ {
+ if (!isValidConnectorIdentifier(connector_identifier))
+ {
+ throw new ConnectorFactoryException("The connector '" + connector_identifier + "' couldn't be found in the list of available connectors.");
+ }
+
+ SettingsReader settings_ = null;
+ try
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ catch (SettingsException e)
+ {
+ String log_message = "Can not load signature settings. Cause:\n" + e.getMessage();
+ logger_.error(log_message);
+ throw new RuntimeException(e);
+ }
+
+ String value = settings_.getValueFromKey(connector_identifier + "." + availability_key);
+ if (value == null)
+ {
+ return default_value;
+ }
+ return value.equals("true");
+ }
+
+ /**
+ * Tells, if the connector is available for being used in the Commandline
+ * (synchron) environment.
+ *
+ * <p>
+ * A connector is available for commandline processing if it requires no
+ * active user interaction for being executed or if it handles the user
+ * interaction itself.
+ * </p>
+ * <p>
+ * A commandline connector is executed synchronously. The client waits until
+ * the Connector has finished.
+ * </p>
+ * <p>
+ * Usually a synchron connector can also be used in a web environment.
+ * </p>
+ * <p>
+ * Examples for commandline connectors are: MOA, BKU. A1 is not suitible for
+ * commandline because it requires HTTP/HTML interaction, log in, etc.
+ * </p>
+ *
+ * @return Returns true, if the Connector is available for Commandline
+ * processing.
+ */
+ public static boolean isAvailableForCommandline(String connector_identifier) throws ConnectorFactoryException
+ {
+ return getAvailabilityUsingDefault(connector_identifier, ConnectorConfigurationKeys.AVAILABLE_FOR_COMMANDLINE, false);
+ }
+
+ /**
+ * Tells, if the Connector is available for being used in a Web (asynchron,
+ * local) environment.
+ *
+ * <p>
+ * A connector is available for Web if it can be used in a web environment.
+ * Often a web connector is also a local connector.
+ * </p>
+ * <p>
+ * Typical examples are the local BKU and A1. The later requires HTML log in
+ * and session handling.
+ * </p>
+ *
+ * @return Returns true, if the Connector is available for the Web
+ * application.
+ */
+ public static boolean isAvailableForWeb(String connector_identifier) throws ConnectorFactoryException
+ {
+ return getAvailabilityUsingDefault(connector_identifier, ConnectorConfigurationKeys.AVAILABLE_FOR_WEB, false);
+ }
+
+ /**
+ * Tells, if the given connector is local.
+ *
+ * @param connector_identifier
+ * The connector.
+ * @return Returns true, if the given connector is local, false otherwise.
+ * @throws ConnectorFactoryException
+ * F.e.
+ */
+ public static boolean isConnectorLocal(String connector_identifier) throws ConnectorFactoryException
+ {
+ return connector_identifier.equals("bku") || connector_identifier.equals("a1");
+ }
+
+ /**
+ * Tells, if the given connector needs or produces SIG_IDs.
+ *
+ * <p>
+ * This method is used when pre formatted signature blocks have to be created
+ * that have to know if there will be a SIG_ID field or not.
+ * </p>
+ * <p>
+ * Connectors like BKU produce SIG_IDs when signing that are needed when
+ * verifying.
+ * </p>
+ *
+ * @param connector
+ * The connector.
+ * @return Returns true, if the given connector uses SIG_IDs, false otherwise.
+ */
+ public static boolean needsSIG_ID(String connector)
+ {
+ return !connector.equals("moa");
+ }
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorInformation.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorInformation.java
new file mode 100644
index 0000000..5855fec
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/ConnectorInformation.java
@@ -0,0 +1,89 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: ConnectorInformation.java,v 1.2 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.Serializable;
+
+/**
+ * Holds the information of one connectior.
+ *
+ * <p>
+ * An implementation of the Connector interface must provide a public static
+ * final ConnectorInformation field named
+ * ConnectorFactory#CONNECTOR_INFORMATION_FIELD_NAME that provides the
+ * information about this connector to the system.
+ * </p>
+ *
+ * @see at.knowcenter.wag.egov.egiz.sig.ConnectorFactory
+ *
+ * @author wprinz
+ */
+public class ConnectorInformation implements Serializable
+{
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = 5692836392376853268L;
+
+ /**
+ * The short identifier of the connector (e.g. "bku").
+ */
+ protected String connector_identifiert = null;
+
+ /**
+ * The user suitable description of the connector (e.g.
+ * "B&uuml;rgerkartenumgebung").
+ */
+ protected String connector_description = null;
+
+ /**
+ * Constructor that initializes this object.
+ *
+ * @param identifier
+ * The short identifier of the connector (e.g. "bku").
+ * @param description
+ * The user suitable description of the connector (e.g.
+ * "B&uuml;rgerkartenumgebung").
+ */
+ public ConnectorInformation(String identifier, String description)
+ {
+ this.connector_identifiert = identifier;
+ this.connector_description = description;
+ }
+
+ /**
+ * Returns the identifier of this connector.
+ *
+ * @return Returns the identifier of this connector.
+ */
+ public String getIdentifier()
+ {
+ return this.connector_identifiert;
+ }
+
+ /**
+ * Returns the description if this connector.
+ *
+ * @return Returns the description if this connector.
+ */
+ public String getDescription()
+ {
+ return this.connector_description;
+ }
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/DummyLDAPAPI.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/DummyLDAPAPI.java
new file mode 100644
index 0000000..7e0834e
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/DummyLDAPAPI.java
@@ -0,0 +1,70 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: DummyLDAPAPI.java,v 1.3 2006/10/31 08:18:56 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.File;
+import java.io.FileInputStream;
+
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+
+/**
+ * This is just a dummy implementation until the real Egiz LDAP API is
+ * implemented.
+ *
+ * @author wprinz
+ */
+public class DummyLDAPAPI
+{
+ String url_ = null;
+
+ public DummyLDAPAPI(String url)
+ {
+ this.url_ = url;
+ }
+
+ public String getURL()
+ {
+ return this.url_;
+ }
+
+ public byte[] loadCertificateFromLDAP(String serial_number, String issuer)
+ {
+ //logger.debug("LDAP: serial_number = " + serial_number);
+ //logger.debug("LDAP: issuer = " + issuer);
+
+ byte[] data = null;
+ if (serial_number.equals("153868") && issuer.equals("CN=a-sign-TEST-Premium-Sig-01,OU=a-sign-TEST-Premium-Sig-01,O=A-Trust Ges. f. Sicherheitssysteme im elektr. Datenverkehr GmbH,C=AT"))
+ {
+ try
+ {
+ File test_file = new File(SettingsReader.CERT_PATH + File.separator + "ldap_test_cert.der");
+ data = new byte[(int) test_file.length()];
+ FileInputStream fis = new FileInputStream(test_file);
+ fis.read(data);
+ fis.close();
+ }
+ catch (Exception e)
+ {
+ e.printStackTrace();
+ data = null;
+ }
+ }
+
+ return data;
+ }
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java
new file mode 100644
index 0000000..13e0b65
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/LocalConnector.java
@@ -0,0 +1,117 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: LocalConnector.java,v 1.2 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+
+/**
+ * A local connector is a refinement of a "normal" Connector that allows to
+ * explicitely do the request on a local client.
+ *
+ * <p>
+ * Basically the sign and verify procedures of this connector are split into
+ * three groups:
+ * </p>
+ * <ol>
+ * <li>Prepare the request to the local service.</li>
+ * <li>Carry out the request on the local client.</li>
+ * <li>Analyze the response from the local client.</li>
+ * </ol>
+ * <p>
+ * Usually the preparation and the analyzation are carried out on the server,
+ * whereas the connection to the local service is made from the local client.
+ * </p>
+ *
+ * @author wprinz
+ */
+public interface LocalConnector extends Connector
+{
+ /**
+ * Prepares the sign request string.
+ *
+ * @param user_name
+ * The user name.
+ * @param sign_text
+ * The text to be signed.
+ * @param signature_type
+ * The type of the signature.
+ * @return Returns the request string to be sent to the local service.
+ * @throws SignatureException
+ * F.e.
+ */
+ public String prepareSignRequest(String user_name, String sign_text,
+ String signature_type) throws SignatureException;
+
+ /**
+ * Prepares the verify request string.
+ *
+ * @param signed_text
+ * The signed text to be verified.
+ * @param signature_object
+ * The SignatureObject.
+ * @return Returns the request string.
+ * @throws SignatureException
+ * F.e.
+ */
+ public String prepareVerifyRequest(String signed_text,
+ SignatureObject signature_object) throws SignatureException;
+
+ /**
+ * Analyzes the sign response string.
+ *
+ * @param response_string
+ * The response string from the local service.
+ * @param signature_type
+ * The type of the signature.
+ * @return Returns the SignatureObject of the sign request.
+ * @throws SignatureException
+ * F.e.
+ */
+ public SignatureObject analyzeSignResponse(String response_string,
+ String signature_type) throws SignatureException;
+
+ /**
+ * Analyzes the verify response string.
+ *
+ * @param response_string
+ * The response string from the local service.
+ * @return Returns the SignatureResponse of the verify request.
+ * @throws SignatureException
+ * F.e.
+ */
+ public SignatureResponse analyzeVerifyResponse(String response_string) throws SignatureException;
+
+ /**
+ * Returns the sign URL of the local service.
+ *
+ * @param profile
+ * The signature type the URL should be retrieved from.
+ * @return Returns the sign URL of the local service.
+ */
+ public String getSignURL(String profile);
+
+ /**
+ * Returns the verify URL of the local service.
+ *
+ * @param profile
+ * The signature type the URL should be retrieved from.
+ * @return Returns the verify URL of the local service.
+ */
+ public String getVerifyURL(String profile);
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureBlock.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureBlock.java
new file mode 100644
index 0000000..1902458
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureBlock.java
@@ -0,0 +1,306 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureBlock.java,v 1.4 2006/10/31 08:18:56 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+
+/**
+ * This method is to analyse a signature block string. It searches for
+ * configured signature types while compairing defined key words with the text.
+ *
+ * @author wlackner
+ */
+public class SignatureBlock
+{
+
+ /**
+ * Start index of the signature block text.
+ */
+ private int startIndex_ = -1;
+
+ /**
+ * End index of the signature block text.
+ */
+ private int endIndex_ = -1;
+
+ /**
+ * The type of the signature block.
+ */
+ private String type_ = null;
+
+ /**
+ * The signature type definition object.
+ */
+ private SignatureTypeDefinition sigTypeDef_ = null;
+
+ /**
+ * The signature block string.
+ */
+ private String signatureString_ = null;
+
+ /**
+ * The signature object build by the signature string using the signture
+ * definition.
+ */
+ private SignatureObject signatureObject_ = null;
+
+ /**
+ * A list of configured signature types.
+ */
+ List signatureTypes_ = null;
+
+ /**
+ * A list of found keys in the signature block string.
+ */
+ Map foundKeys_ = new HashMap();
+
+ int maxSize_ = -1;
+
+ /**
+ * The default constructor to analyse a signature block string. It uses a
+ * predefined signature type list to assign the text block to signature type.
+ * The analyse method have to be call separately -->
+ * separateBlockFromRawText()
+ *
+ * @param signatureTypes
+ */
+ public SignatureBlock(List signatureTypes)
+ {
+ signatureTypes_ = signatureTypes;
+ }
+
+ /**
+ * This method checks if all required keys are found in the signature block
+ * string.
+ *
+ * @param foundKeys
+ * the keys that are found in the singnature block string
+ * @return true if all required keys are found, false otherwise
+ */
+ private boolean checkRequiredFields(Map foundKeys)
+ {
+ String[] req_keys = SignatureTypes.REQUIRED_SIG_KEYS;
+ for (int req_idx = 0; req_idx < req_keys.length; req_idx++)
+ {
+ String key = req_keys[req_idx];
+ // SIG_ID could be optional --> only set in BKU signed documents
+ if (key.equals(SignatureTypes.SIG_ID))
+ {
+ continue;
+ }
+ // logger.debug("check:" + key + "=" + foundKeys.get(key));
+ if (foundKeys.get(key) == null)
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * This method is the base method to analyse a raw text separating a signature
+ * block string from the raw text. It searches for corresponding signature
+ * types from back to front in the raw text. Therefore a revert list of
+ * multiple signations can be extracted calling this method more than one
+ * times. The method extracts the start and end postition of a found signature
+ * block and extracts all keys used in that block. If all required fields are
+ * found a successful separation is done and can be access calling the method
+ * getStartIndex, getEndIndex, getType, getSignatureObject.
+ *
+ * @param rawText
+ * the raw text to separate a signature block from
+ * @return true if a separation has done successful false if no signature
+ * block can be found
+ */
+ public boolean separateBlockFromRawText(String rawText, boolean old_style)
+ {
+ endIndex_ = rawText.length();
+ boolean found_type = false;
+ for (int sig_type_idx = 0; sig_type_idx < signatureTypes_.size(); sig_type_idx++)
+ {
+ int last_index = endIndex_;
+ SignatureTypeDefinition sig_type_def = (SignatureTypeDefinition) signatureTypes_.get(sig_type_idx);
+ //logger.debug("Try sep type:" + sig_type_def.getType());
+
+ Vector keys = sig_type_def.getRevertSortedKeys();
+ Vector captions = sig_type_def.getRevertSortedCaptions();
+ Map found_keys = new HashMap();
+ for (int key_idx = 0; key_idx < keys.size(); key_idx++)
+ {
+ String key = (String) keys.get(key_idx);
+ if (old_style && key.equals(SignatureTypes.SIG_KZ))
+ {
+ // If separating the old style way - skip The "Kennzeichnung"
+ // key, because it wasn't present in old profiles.
+ continue;
+ }
+ String caption = (String) captions.get(key_idx);
+ int found_idx = rawText.lastIndexOf(caption);
+ //logger.debug("Try find:" + sig_type_def.getType() + "." + key + "." + caption + " at=" + found_idx);
+ if (found_idx >= 0 && found_idx < last_index)
+ {
+ if (key.equals(SignatureTypes.SIG_ID))
+ {
+ //logger.debug("store SIG_ID, but don't decrease last index:" + sig_type_def.getType() + "." + key + "." + caption + " at=" + found_idx);
+ found_keys.put(key, new Integer(found_idx));
+ // don't decrease last index as SIG_ID is not necessarily persistent
+ }
+ else
+ {
+ //logger.debug("store:" + sig_type_def.getType() + "." + key + "." + caption + " at=" + found_idx);
+ found_keys.put(key, new Integer(found_idx));
+ last_index = found_idx;
+ }
+ }
+ }
+ if (checkRequiredFields(found_keys) && found_keys.size() > maxSize_)
+ {
+ foundKeys_ = found_keys;
+ sigTypeDef_ = sig_type_def;
+ type_ = sig_type_def.getType();
+ startIndex_ = last_index;
+ signatureString_ = rawText.substring(startIndex_, endIndex_);
+ maxSize_ = found_keys.size();
+ found_type = true;
+ }
+ }
+ return found_type;
+ }
+
+ /**
+ * @return Returns the endIndex.
+ */
+ public int getEndIndex()
+ {
+ return endIndex_;
+ }
+
+ /**
+ * @return Returns the signatureObject of the separated signature block.
+ * @throws SignatureException
+ */
+ public SignatureObject getSignatureObject() throws SignatureException
+ {
+ if (signatureObject_ == null && foundKeys_ != null)
+ {
+ signatureObject_ = new SignatureObject();
+ try
+ {
+ signatureObject_.setSigType(type_);
+ signatureObject_.initByType();
+ }
+ catch (SignatureTypesException e)
+ {
+ SignatureException se = new SignatureException(101, "Can ot set signation type:" + type_, e);
+ throw se;
+ }
+ String sig_text = signatureString_;
+ Vector revert_keys = sigTypeDef_.getRevertSortedKeys();
+ Vector revert_captions = sigTypeDef_.getRevertSortedCaptions();
+ for (int key_idx = 0; key_idx < revert_keys.size(); key_idx++)
+ {
+ String key = (String) revert_keys.get(key_idx);
+ String caption = (String) revert_captions.get(key_idx);
+ int start_idx = sig_text.lastIndexOf(caption);
+ if (start_idx >= 0)
+ {
+ int sep_idx = start_idx + caption.length();
+ // logger.debug(sig_text);
+ // logger.debug("caption:" + caption + " start_idx:" + start_idx
+ // + " length:" +
+ // sig_text.length());
+ String value = sig_text.substring(sep_idx);
+ // logger.debug("key:" + key + " value:" + value);
+ signatureObject_.setSigValueCaption(key, value, caption);
+ sig_text = sig_text.substring(0, start_idx);
+ }
+ }
+ }
+ return signatureObject_;
+ }
+
+ /**
+ * @return Returns the startIndex.
+ */
+ public int getStartIndex()
+ {
+ return startIndex_;
+ }
+
+ /**
+ * @return Returns the type.
+ */
+ public String getType()
+ {
+ return type_;
+ }
+
+// /**
+// * @param endIndex
+// * The endIndex to set.
+// */
+// private void setEndIndex(int endIndex)
+// {
+// endIndex_ = endIndex;
+// }
+//
+// /**
+// * @param startIndex
+// * The startIndex to set.
+// */
+// private void setStartIndex(int startIndex)
+// {
+// startIndex_ = startIndex;
+// }
+//
+// /**
+// * @param type
+// * The type to set.
+// */
+// private void setType(String type)
+// {
+// type_ = type;
+// }
+
+ /**
+ * The standard toString method. Used for interal tests only.
+ */
+ public String toString()
+ {
+ String strg = "";
+ strg += "Type:" + type_ + "\n";
+ strg += "Start index:" + startIndex_ + "\n";
+ strg += "End index:" + endIndex_ + "\n";
+ strg += signatureString_ + "\n";
+ strg += sigTypeDef_ + "\n";
+ try
+ {
+ strg += getSignatureObject().toString();
+ }
+ catch (SignatureException e)
+ {
+ }
+ return strg;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureEntry.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureEntry.java
new file mode 100644
index 0000000..2782f2b
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureEntry.java
@@ -0,0 +1,155 @@
+/*
+ * <copyright>
+ * Copyright (c) 2006 by Know-Center, Graz, Austria
+ * </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
+ * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
+ * OR NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES
+ * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
+ * THIS SOFTWARE OR ITS DERIVATIVES.
+ *
+ * $Id: SignatureEntry.java,v 1.3 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.Serializable;
+
+/**
+ * This class is to store a signature entry. The signature entry is 3-tupel. A key that is defined
+ * or declarated in the settings file, an optional caption or a value. <br>
+ * An additional helper value is a marker for the start index of the key, if the key is found in an
+ * analysing process extracting captions and values from a raw signature text.
+ *
+ * @author wlackner
+ * @see at.knowcenter.wag.egov.egiz.sig.SignatureObject
+ */
+public class SignatureEntry implements Serializable {
+
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = 4640380069301731879L;
+
+ /**
+ * The signature key.
+ */
+ private String key_ = null;
+ /**
+ * The signature caption for the key found or set in the signature text.
+ */
+ private String caption_ = null;
+ /**
+ * The signature value for the key found or set in the signature text.
+ */
+ private String value_ = null;
+ /**
+ * The starting index position of the key if it is found in the signature text.
+ */
+ private int startIndex_ = -1;
+
+ /**
+ * The empty constructor.
+ */
+ public SignatureEntry() {
+ }
+
+ /**
+ * A new <code>SignatureEntry</code> init with the key.
+ *
+ * @param key
+ */
+ public SignatureEntry(String key) {
+ key_ = key;
+ }
+
+ /**
+ * Returns the caption off the current key.
+ *
+ * @return Returns the caption.
+ */
+ public String getCaption() {
+ return caption_;
+ }
+
+ /**
+ * Set the caption of the current key.
+ *
+ * @param caption The caption to set.
+ */
+ public void setCaption(String caption) {
+ caption_ = caption;
+ }
+
+ /**
+ * Return the current key.
+ *
+ * @return Returns the key.
+ */
+ public String getKey() {
+ return key_;
+ }
+
+ /**
+ * Set the current key.
+ *
+ * @param key The key to set.
+ */
+ public void setKey(String key) {
+ key_ = key;
+ }
+
+ /**
+ * Return the start position of the key that caption is found in the signature text.
+ *
+ * @return Returns the startIndex.
+ */
+ public int getStartIndex() {
+ return startIndex_;
+ }
+
+ /**
+ * Set the start position of the current key.
+ *
+ * @param startIndex The startIndex to set.
+ */
+ public void setStartIndex(int startIndex) {
+ startIndex_ = startIndex;
+ }
+
+ /**
+ * Return the value of the current key.
+ *
+ * @return Returns the value.
+ */
+ public String getValue() {
+ return value_;
+ }
+
+ /**
+ * Set the value of the current key.
+ *
+ * @param value The value to set.
+ */
+ public void setValue(String value) {
+ value_ = value;
+ }
+
+ /**
+ * The toString method, used for tests or debugging.
+ */
+ public String toString() {
+ String the_string = "";
+ the_string += "\n Key:" + key_;
+ the_string += "\nCaption:" + caption_;
+ the_string += "\n Value:" + value_;
+// the_string += "\nStart I:" + startIndex_;
+ return the_string;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureFieldDefinition.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureFieldDefinition.java
new file mode 100644
index 0000000..eacf575
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureFieldDefinition.java
@@ -0,0 +1,80 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureFieldDefinition.java,v 1.1 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.Serializable;
+
+/**
+ * This class contains the information about one field in the signature block.
+ *
+ * <p>
+ * E.g. Field "Issuer" could have the caption "Aussteller", the value null and
+ * the placeholder length of 500.
+ * </p>
+ *
+ * @author wprinz
+ */
+public class SignatureFieldDefinition implements Serializable
+{
+
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = -46020173047777315L;
+
+ /**
+ * The key identifier of this field.
+ */
+ public String field_name = null;
+
+ /**
+ * The static caption of the field.
+ */
+ public String caption = null;
+
+ /**
+ * The static value of the field.
+ *
+ * <p>
+ * Null means that this field has no static value and must be filled out.
+ * </p>
+ */
+ protected String value = null;
+
+ /**
+ * If the field is not static and has to be filled out, this gives the
+ * length of the placeholder that is reserved for filling out.
+ *
+ * <p>
+ * This has to be large enough so that it can hold the whole value to be
+ * filled out.
+ * </p>
+ */
+ public int placeholder_length = -1;
+
+ /**
+ * Stores the three byte abbreviation code of this field's field name.
+ */
+ //public byte [] brev = null;
+
+ public String toString()
+ {
+ return this.field_name + ": caption=" + this.caption + ", value=" + this.value + ", phlen=" + this.placeholder_length;
+ }
+
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java
new file mode 100644
index 0000000..087ce4e
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureObject.java
@@ -0,0 +1,1499 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureObject.java,v 1.7 2006/10/31 08:18:56 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.io.UnsupportedEncodingException;
+import java.util.ArrayList;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Vector;
+
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.PdfASID;
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.InvalidIDException;
+import at.knowcenter.wag.egov.egiz.exceptions.NormalizeException;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+import at.knowcenter.wag.egov.egiz.framework.SignatorFactory;
+import at.knowcenter.wag.egov.egiz.table.Entry;
+import at.knowcenter.wag.egov.egiz.table.Style;
+import at.knowcenter.wag.egov.egiz.table.Table;
+import at.knowcenter.wag.egov.egiz.tools.CodingHelper;
+import at.knowcenter.wag.egov.egiz.tools.FileHelper;
+import at.knowcenter.wag.egov.egiz.tools.Normalizer;
+
+/**
+ * This class represents the abstract signature object. It contains all methods
+ * reading the definitions from the settings file, analyse them and build the
+ * abstract signature table. <br>
+ * All values that build or used by the signation creation process, call the
+ * external services, can read or set separately. All other values are defined
+ * in the settings file.
+ *
+ * @author wlackner
+ */
+public class SignatureObject implements Serializable
+{
+
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = -3257189232362254713L;
+
+ /**
+ * The system file separator char
+ */
+ private static final String FILE_SEP = System.getProperty("file.separator");
+
+ /**
+ * The certificate extension
+ */
+ private static final String CERT_FILE_EXTENSION = ".der";
+
+ /**
+ * certificate import dir
+ */
+ private static final String CERT_ADD_DIR = "tobeadded";
+
+ /**
+ * The default style definition for images.
+ */
+ private Style defaultImageStyle_ = new Style();
+
+ /**
+ * The default style definition for captions.
+ */
+ private Style defaultCaptionStyle_ = new Style();
+
+ /**
+ * The default style definition for values.
+ */
+ private Style defaultValueStyle_ = new Style();
+
+ /**
+ * Standard key get/set the signature meta informations
+ */
+ public static final String SIG_META = "SIG_META";
+
+ /**
+ * Standard key get/set the certification value
+ */
+ public static final String SIG_CER = "SIG_CER";
+
+ /**
+ * Standard key get/set the certification digest value
+ */
+ public static final String SIG_CER_DIG = "SIG_CER_DIG";
+
+ private X509Cert x509Cert_ = null;
+
+ // public static final String SIG_RES = "SIG_RES";
+ // dummy value for debugging only
+ private String sigResponse_ = null;
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(SignatureObject.class);
+
+ /**
+ * The normalizer reference
+ */
+ private Normalizer normalizer_ = null;
+
+ /**
+ * The settings reader reference
+ */
+ private SettingsReader settings_ = null;
+
+ // /**
+ // * The reference to the settings property tree
+ // */
+ // private PropertyTree pTree_ = null;
+ /**
+ * The current signature type used reading and analysing the property tree
+ */
+ private String sigType_ = null;
+
+ /**
+ * Reference from signature key to there corresponding value
+ */
+ private Hashtable sigEntries_ = new Hashtable(8);
+
+ /**
+ * The abstract table representation
+ */
+ private Table sigTable_ = null;
+
+ // private HashMap sigIndexMap_ = new HashMap();
+
+ /**
+ * Path value storing and fetching the certificates
+ */
+ private String certPath_ = null;
+
+ /**
+ * the signature definition object
+ */
+ private SignatureTypeDefinition signatureDefinition_ = null;
+
+ /**
+ * The raw xml response from the connector that was used to set the values in
+ * this SignatureObject.
+ *
+ * <p>
+ * This is set by the Connector so that signing Applications can use the
+ * returned XML values.
+ * </p>
+ */
+ protected String raw_signature_response = null;
+
+ /**
+ * The empty constructor. It initilize the normlizer, load the settings and
+ * set the default styles.
+ *
+ * @throws SignatureException
+ * ErrorCode:101, 400
+ */
+ public SignatureObject() throws SignatureException
+ {
+ initNormalizer();
+ loadSettings();
+ setDefaultStyles();
+ }
+
+ /**
+ * This method initialize the normalizer
+ *
+ * @throws SignatureException
+ * ErrorCode:400
+ */
+ private void initNormalizer() throws SignatureException
+ {
+ try
+ {
+ normalizer_ = new Normalizer();
+ }
+ catch (NormalizeException e)
+ {
+ SignatureException se = new SignatureException(400, "Normalizer can not be initialized", e);
+ throw se;
+ }
+ }
+
+ /**
+ * This method load the signature definitions
+ *
+ * @throws SignatureException
+ * ErrorCode:101
+ */
+ private void loadSettings() throws SignatureException
+ {
+ if (settings_ == null)
+ {
+ try
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ catch (SettingsException e)
+ {
+ String log_message = "Can not load pdf signature settings. Cause:\n" + e.getMessage();
+ logger_.error(log_message);
+ SignatureException se = new SignatureException(101, log_message, e);
+ se.setErrorCode(101);
+ throw se;
+ }
+ }
+ // pTree_ = settings_.getPTree();
+
+ certPath_ = SettingsReader.CERT_PATH;
+ }
+
+ /**
+ * This method set the default styles for images, captions and values.
+ */
+ private void setDefaultStyles()
+ {
+ defaultImageStyle_.setPadding(3);
+ defaultImageStyle_.setHAlign(Style.CENTER);
+ defaultImageStyle_.setVAlign(Style.MIDDLE);
+ defaultImageStyle_.setBgColor(null);
+
+ defaultCaptionStyle_.setHAlign(Style.CENTER);
+ defaultCaptionStyle_.setVAlign(Style.MIDDLE);
+
+ defaultValueStyle_.setVAlign(Style.MIDDLE);
+ }
+
+ /**
+ * Dummy getter Method for debugging only
+ *
+ * @return response string
+ */
+ public String getSigResponse()
+ {
+ return sigResponse_;
+ }
+
+ /**
+ * Dummy setter Method for debugging only
+ *
+ * @param sigRespone
+ * store the response string
+ */
+ public void setSigResponse(String sigRespone)
+ {
+ sigResponse_ = sigRespone;
+ }
+
+ /**
+ * This method set the signature type.
+ *
+ * @param sigType
+ * the signature type to be set
+ * @throws SignatureTypesException
+ */
+ public void setSigType(String sigType) throws SignatureTypesException
+ {
+ SignatureTypes sig_types = SignatureTypes.getInstance();
+ signatureDefinition_ = sig_types.getSignatureTypeDefinition(sigType_);
+ sigType_ = sigType;
+ }
+
+ /**
+ * Returns the default signation type
+ *
+ * @return the key for the default signature definition, if the key is not
+ * found it returns null
+ */
+ private String getDefaultSigType()
+ {
+ return settings_.getSetting(SignatureTypes.DEFAULT_TYPE, null);
+ }
+
+ /**
+ * This method checks if a given signature key is realy a defined signature
+ * key.
+ *
+ * @param sigKey
+ * the key to check
+ * @return true if the key is correct, false if the given key is not defined
+ */
+ public boolean isSigKey(String sigKey)
+ {
+ return signatureDefinition_.contains(sigKey);
+ }
+
+ /**
+ * This method adds an signaton value to the entry cache. If a key is not in
+ * the cache a new signature entry is createad. Therefor the method return
+ * true. <br>
+ * The value that has to be set would be normalized! <br>
+ * <b>If the key equals to <code>SIG_VALUE</code> all whitespaces are
+ * removed! </b> <br>
+ *
+ * @param key
+ * the key to be set
+ * @param value
+ * the value to be set
+ * @return <code>true</code> if a new signature value is created,
+ * <code>false</code> otherwise
+ */
+ public boolean setSigValue(String key, String value)
+ {
+ SignatureEntry sig_entry = null;
+ boolean is_new = false;
+ if (sigEntries_.containsKey(key))
+ {
+ sig_entry = (SignatureEntry) sigEntries_.get(key);
+ }
+ else
+ {
+ sig_entry = new SignatureEntry(key);
+ sigEntries_.put(key, sig_entry);
+ is_new = true;
+ }
+ value = normalizer_.normalize(value);
+ if (SignatureTypes.SIG_VALUE.equals(key) || SignatureTypes.SIG_ID.equals(key) || SignatureTypes.SIG_NUMBER.equals(key))
+ {
+ value = removeAllWhiteSpaces(value);
+ }
+ sig_entry.setValue(value);
+ return is_new;
+ }
+
+ public boolean setValueBruteForce(String key, String value)
+ {
+ SignatureEntry sig_entry = null;
+ boolean is_new = false;
+ if (sigEntries_.containsKey(key))
+ {
+ sig_entry = (SignatureEntry) sigEntries_.get(key);
+ }
+ else
+ {
+ sig_entry = new SignatureEntry(key);
+ sigEntries_.put(key, sig_entry);
+ is_new = true;
+ }
+ sig_entry.setValue(value);
+ return is_new;
+ }
+
+ /**
+ * Set the value and the caption to given key.
+ *
+ * @param key
+ * the key of the signature object
+ * @param value
+ * the value of the given key
+ * @param caption
+ * the caption of the given key
+ */
+ public void setSigValueCaption(String key, String value, String caption)
+ {
+ setSigValue(key, value);
+ SignatureEntry sig_entry = (SignatureEntry) sigEntries_.get(key);
+ sig_entry.setCaption(caption);
+ }
+
+ /**
+ * This method returns a value for a given signature key. If the key equals to
+ * <code>SIG_NORM</code> and the value is <code>null</code> the version
+ * string of the current normalizer is returned!
+ *
+ * @param key
+ * the key to get the value for
+ * @return a value for the given key
+ */
+ public String getSigValue(String key)
+ {
+ String value = null;
+ if (sigEntries_.containsKey(key))
+ {
+ value = ((SignatureEntry) sigEntries_.get(key)).getValue();
+ }
+ if (value == null && SignatureTypes.SIG_NORM.equals(key))
+ {
+ value = normalizer_.getVersion();
+ }
+ return value;
+ }
+
+ /**
+ * Sets the "Kennzeichnung".
+ *
+ * @param kz
+ * The "Kennzeichnung" to be set.
+ */
+ public void setKZ(PdfASID kz)
+ {
+ setSigValue(SignatureTypes.SIG_KZ, kz.toString());
+ }
+
+ /**
+ * Returns the "Kennzeichnung" of this signature.
+ *
+ * @return Returns the "Kennzeichnung" of this signature. Returns null if
+ * there is no "Kennzeichnung" or it is not recognized by this
+ * application.
+ */
+ public PdfASID getKZ() throws InvalidIDException
+ {
+ String kz_string = getSigValue(SignatureTypes.SIG_KZ);
+ if (kz_string == null)
+ {
+ return null;
+ }
+ PdfASID kz = null;
+ try
+ {
+ kz = new PdfASID(kz_string);
+ }
+ catch (InvalidIDException e)
+ {
+ e.printStackTrace();
+ }
+ return kz;
+ }
+
+ /**
+ * This method returns a caption for a given signature key. If the key exists
+ * and the coresponding value is <code>null</code> the key itself is
+ * returned as caption! If the key does not exist the method returns
+ * <code>null</code>.
+ *
+ * @param key
+ * the key to get the caption for
+ * @return a caption for the given key
+ */
+ private String getSigCaption(String key)
+ {
+ String caption = null;
+ if (sigEntries_.containsKey(key))
+ {
+ caption = ((SignatureEntry) sigEntries_.get(key)).getCaption();
+ if (caption == null)
+ {
+ caption = key;
+ }
+ }
+ return caption;
+ }
+
+ /**
+ * @return Returns the SignationType.
+ */
+ public String getSignationType()
+ {
+ if (sigType_ == null)
+ {
+ sigType_ = getDefaultSigType();
+ }
+ return sigType_;
+ }
+
+ /**
+ * @return Returns the SignationDate.
+ */
+ public String getSignationDate()
+ {
+ return getSigValue(SignatureTypes.SIG_DATE);
+ }
+
+ /**
+ * @param sigDate
+ * The SignationDate to set.
+ */
+ public void setSignationDate(String sigDate)
+ {
+ setSigValue(SignatureTypes.SIG_DATE, sigDate);
+ }
+
+ /**
+ * @return Returns the SignationName.
+ */
+ public String getSignationName()
+ {
+ return getSigValue(SignatureTypes.SIG_NAME);
+ }
+
+ /**
+ * @param sigName
+ * The SignationName to set.
+ */
+ public void setSignationName(String sigName)
+ {
+ setSigValue(SignatureTypes.SIG_NAME, sigName);
+ }
+
+ /**
+ * @return Returns the SignationNormVersion.
+ */
+ public String getSignationNormVersion()
+ {
+ return getSigValue(SignatureTypes.SIG_NORM);
+ }
+
+ /**
+ * @param sigNormVersion
+ * The SignationNormVersion to set.
+ */
+ public void setSignationNormVersion(String sigNormVersion)
+ {
+ setSigValue(SignatureTypes.SIG_NORM, sigNormVersion);
+ }
+
+ /**
+ * @return Returns the SignationIssuer.
+ */
+ public String getSignationIssuer()
+ {
+ String issuer = getSigValue(SignatureTypes.SIG_ISSUER);
+ X509Cert cert = loadCertificate(getSigValue(SignatureTypes.SIG_NUMBER), issuer);
+ if (cert != null)
+ {
+ setSigValue(SignatureTypes.SIG_ISSUER, cert.getIssuerName());
+ setSigValue(SIG_CER, cert.getCertString());
+ setSigValue(SIG_CER_DIG, cert.getCertDigest());
+ x509Cert_ = cert;
+ }
+ issuer = getSigValue(SignatureTypes.SIG_ISSUER);
+ return issuer;
+ }
+
+ /**
+ * @param sigIssuer
+ * The SignationIssuer to set.
+ */
+ public void setSignationIssuer(String sigIssuer)
+ {
+ setSigValue(SignatureTypes.SIG_ISSUER, sigIssuer);
+ }
+
+ /**
+ * @return Returns the SignationValue.
+ */
+ public String getSignationValue()
+ {
+ return getSigValue(SignatureTypes.SIG_VALUE);
+ }
+
+ /**
+ * @param sigValue
+ * The SignationValue to set.
+ */
+ public void setSignationValue(String sigValue)
+ {
+ setSigValue(SignatureTypes.SIG_VALUE, sigValue);
+ }
+
+ /**
+ * @return the reference to the signature label
+ */
+ public String getOfficialSeal()
+ {
+ return getSigValue(SignatureTypes.SIG_LABEL);
+ }
+
+ /**
+ * @param serialNumber
+ * The serial number of the signature to set
+ */
+ public void setSignationSerialNumber(String serialNumber)
+ {
+ setSigValue(SignatureTypes.SIG_NUMBER, serialNumber);
+ }
+
+ /**
+ * @return sigNumber the serial number of the signature
+ */
+ public String getSignationSerialNumber()
+ {
+ return getSigValue(SignatureTypes.SIG_NUMBER);
+ }
+
+ /**
+ * @param certDigest
+ * set the digest value for the X509Certificate
+ */
+ public void setX509CertificateDigest(String certDigest)
+ {
+ setSigValue(SIG_CER_DIG, certDigest);
+ }
+
+ /**
+ * This method load the current certificate getting the current SerialNumber
+ * and the current SignationIssuer. <br>
+ * It stores back the SignationIssuer, X509Certificate and
+ * X509CertificateDigest
+ */
+ private void loadCurrentCert()
+ {
+ X509Cert cert = loadCertificate(getSignationSerialNumber(), getSignationIssuer());
+ if (cert != null)
+ {
+ setSigValue(SignatureTypes.SIG_ISSUER, cert.getIssuerName());
+ setSigValue(SIG_CER, cert.getCertString());
+ setSigValue(SIG_CER_DIG, cert.getCertDigest());
+ x509Cert_ = cert;
+ }
+ }
+
+ /**
+ * @return the current X509CertificateDigest value.
+ */
+ public String getX509CertificateDigest()
+ {
+ String dig = getSigValue(SIG_CER_DIG);
+ if (dig == null)
+ {
+ loadCurrentCert();
+ dig = getSigValue(SIG_CER_DIG);
+ }
+ return dig;
+ }
+
+ /**
+ * @return the current X509v3 certificate string
+ */
+ public String getX509CertificateString()
+ {
+ String cert = getSigValue(SIG_CER);
+ if (cert == null)
+ {
+ loadCurrentCert();
+ cert = getSigValue(SIG_CER);
+ }
+ return cert;
+ }
+
+ /**
+ * @param x509Certificate
+ * The X509v3 certificate of the signature to set
+ */
+ public void setX509Certificate(String x509Certificate)
+ {
+ setSigValue(SIG_CER, x509Certificate);
+ storeCertificate(getSignationSerialNumber(), getSignationIssuer(), x509Certificate, getX509CertificateDigest());
+ }
+
+ /**
+ * return the 509v3 certificate of the given serialNumber and the given issuer
+ * string
+ *
+ * @param serialNumber
+ * the serialNumber which the certificates should load
+ * @param issuer
+ * the issuer which the certificates should load
+ * @return the X509v3 certificate string
+ */
+ public String getX509CertificateString(String serialNumber, String issuer)
+ {
+ X509Cert cert = loadCertificate(serialNumber, issuer);
+ if (cert != null)
+ {
+ return cert.getCertString();
+ }
+ return null;
+ }
+
+ public X509Cert getX509Cert(String serialNumber, String issuer)
+ {
+ return loadCertificate(serialNumber, issuer);
+ }
+
+ public X509Cert getX509Cert()
+ {
+ if (x509Cert_ == null)
+ {
+ loadCurrentCert();
+ }
+ return x509Cert_;
+ }
+
+ /**
+ * Set the signation id's build by a BKU signated SignatureObject.
+ *
+ * @param sigIds
+ * the string to store.
+ */
+ public void setSignationIDs(String sigIds)
+ {
+ setSigValue(SignatureTypes.SIG_ID, sigIds);
+ }
+
+ /**
+ * Set the signation id's build by a BKU signated SignatureObject.
+ *
+ * @param sigIds
+ * The sination id's are defined into five parts, that have the same
+ * base as prefix. Therefore the ids's are reduced by the base prefix
+ * and stored in the SignatureObject.
+ */
+ public void setSignationIDs(String[] sigIds)
+ {
+ String join = "";
+ String base = null;
+ for (int arr_idx = 0; arr_idx < sigIds.length; arr_idx++)
+ {
+ String id = sigIds[arr_idx];
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Set BKU id:" + id);
+ }
+ int id_idx = id.lastIndexOf("-");
+ if (arr_idx == 0)
+ {
+ base = id.substring(0, id_idx);
+ }
+ String cur_id = id.substring(id_idx + 1);
+ join += "-" + cur_id;
+ }
+ setSignationIDs(base + "@" + join.substring(1));
+ }
+
+ /**
+ * Checks if the current SignatureObject is siganted by MOA. It checks if the
+ * current SignatureObject has a signation id value.
+ *
+ * @return true if no signation id value is found, false otherwise
+ */
+ public boolean isMOASigned()
+ {
+ return getSignationIds() == null;
+ }
+
+ /**
+ * Tells if this SignatureObject is textual.
+ *
+ * @return Returns true, if it is textual.
+ */
+ public boolean isTextual()
+ {
+ PdfASID kz = null;
+ try
+ {
+ kz = getKZ();
+ }
+ catch (InvalidIDException e)
+ {
+ e.printStackTrace();
+ }
+ if (kz == null)
+ {
+ return true; // must be an old Signature
+ }
+
+ boolean textual = kz.getType().equals(SignatorFactory.TYPE_TEXTUAL);
+ return textual;
+ }
+
+ /**
+ * Tells, if this SignatureObject is binary.
+ *
+ * @return Returns true, if it is binary.
+ */
+ public boolean isBinary()
+ {
+ PdfASID kz = null;
+ try
+ {
+ kz = getKZ();
+ }
+ catch (InvalidIDException e)
+ {
+ e.printStackTrace();
+ }
+ if (kz == null)
+ {
+ return false; // must be an old Signature
+ }
+
+ boolean binary = kz.getType().equals(SignatorFactory.TYPE_BINARY);
+ return binary;
+ }
+
+ /**
+ * Takes the signation id value of the current SignatureObject and split them
+ * into the corresponding id array added with the id-base.
+ *
+ * @return the id array
+ */
+ public String[] getSignationIds()
+ {
+ String sig_ids = getSigValue(SignatureTypes.SIG_ID);
+ if (sig_ids == null || sig_ids.length() == 0)
+ {
+ return null;
+ }
+
+ // int index = sig_ids.indexOf(PdfAS.IDS);
+ // if (index < 0)
+ // {
+ // return null;
+ // }
+ // sig_ids = sig_ids.substring(index + PdfAS.IDS.length());
+ //
+ // if (sig_ids == null || sig_ids.length() == 0)
+ // {
+ // return null;
+ // }
+
+ String[] ids_str = sig_ids.split("@");
+ String base = ids_str[0];
+ String[] ids = ids_str[1].split("-");
+ String[] real_ids = new String[5];
+ real_ids[0] = base + "-" + ids[0];
+ real_ids[1] = "0-" + base + "-" + ids[1];
+ real_ids[2] = "0-" + base + "-" + ids[2];
+ real_ids[3] = "0-" + base + "-" + ids[3];
+ real_ids[4] = "0-" + base + "-" + ids[4];
+ if (logger_.isDebugEnabled())
+ {
+ for (int id_idx = 0; id_idx < real_ids.length; id_idx++)
+ {
+ logger_.debug("Set BKU id:" + real_ids[id_idx]);
+ }
+ }
+ return real_ids;
+ }
+
+ /**
+ * This method normalizes the issuer string to support unique issuer string
+ * for equition. Used to store and find corresponting certificates.
+ * Normalzing: normalizing the string using the normalizer, remove all white
+ * spaces, encode as base64 and replace all "/" chars with "_".
+ *
+ * @param issuer
+ * the issuer string to normalize
+ * @return the normalized issuer string
+ */
+ private String getIssuerFileHash(String issuer)
+ {
+ try
+ {
+ if (issuer != null)
+ {
+ issuer = normalizer_.normalize(issuer);
+ issuer = removeAllWhiteSpaces(issuer);
+ // added the ("UTF-8")
+ issuer = CodingHelper.encodeBase64(CodingHelper.buildDigest(issuer.getBytes("UTF-8")));
+ issuer = issuer.replaceAll("/", "_");
+ }
+ return issuer;
+ }
+ catch (UnsupportedEncodingException e)
+ {
+ e.printStackTrace();
+ throw new RuntimeException(e);
+ }
+ }
+
+ /**
+ * This method imports new certificates into the certstore path.
+ */
+ private void addNewCertificates()
+ {
+ String cert_add_path = certPath_ + CERT_ADD_DIR;
+ File cert_add_dir = new File(cert_add_path);
+ if (cert_add_dir.isDirectory())
+ {
+ File[] cert_files = cert_add_dir.listFiles();
+ for (int cert_file_idx = 0; cert_file_idx < cert_files.length; cert_file_idx++)
+ {
+ File cert_file = cert_files[cert_file_idx];
+ if (cert_file.isFile() && cert_file.canRead())
+ {
+ X509Cert cert = X509Cert.initByFile(cert_file);
+ // System.err.println("isCert:" + cert.isX509Cert() + ":" +
+ // cert_file.getAbsolutePath());
+ if (cert.isX509Cert())
+ {
+ String issuer = cert.getIssuerName();
+ String serial_number = cert.getSerialNumber();
+ String iss_hash = getIssuerFileHash(issuer);
+ String cert_store_path = certPath_ + iss_hash;
+
+ File cert_store_dir = new File(cert_store_path);
+ if (!cert_store_dir.exists())
+ {
+ cert_store_dir.mkdir();
+ }
+ if (cert_store_dir.isDirectory())
+ {
+ String cert_file_name = cert_store_path + FILE_SEP + serial_number + CERT_FILE_EXTENSION;
+ // boolean store =
+ FileHelper.writeToFile(cert_file_name, cert.getCertString());
+ // System.err.println("store:" + store + ":" +
+ // cert_file.getAbsolutePath());
+ }
+ }
+ boolean deleted = cert_file.delete();
+ if (deleted == false)
+ {
+ System.err.println("couldn't delete:" + cert_file.getAbsolutePath());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * This method load a X509v3 certificate from the filesystem. The reference to
+ * the stored certificate is build by the serialNumber and the issuer string.
+ * The issuer string is normalized because if getting this value from a pdf
+ * extraction it can be splited into more sections or necessary spaces are
+ * removed. The real issuer value is stored in the certificates meta file. The
+ * certficate is devided into two files: certificate.der (the binary value)
+ * and the meta information used in SignatureObjects as well in
+ * SignatureImages of a signed pdf-document. The storing path of the
+ * certificate is build by:
+ * <ol>
+ * <li>normalize the issuer string</li>
+ * <li>reduce all white spaces in the normalized issuer string</li>
+ * <li>build a hash value of this reduced string</li>
+ * <li>code this hash value as base64 value</li>
+ * <li>add the base64 normalized issuer hash value to the certificate base
+ * store path</li>
+ * <li>add the serialNumber to the cert path</li>
+ * <li>add the <code>.der</code> extension to get the certificate binary</li>
+ * <li>add the <code>.txt</code> extension to get the meta information of
+ * the certificate</li>
+ * </ol>
+ *
+ * The certificate meta file is build by the base64 coded issuer string and
+ * the cert digest value devided by the <code>@</code> char.
+ *
+ * @param serialNumber
+ * the file name of the certificate .der|.txt
+ * @param issuer
+ * the file path value of the certificate
+ * @return String array: [0]--> issuer string; [1]-->certificate binary;
+ * [2]--> cert digest value
+ */
+ private X509Cert loadCertificate(String serialNumber, String issuer)
+ {
+ addNewCertificates();
+ X509Cert cert = null;
+ if (issuer != null && serialNumber != null)
+ {
+ String iss_hash = getIssuerFileHash(issuer);
+ String cert_store_path = certPath_ + iss_hash;
+ String cert_file_name = cert_store_path + FILE_SEP + serialNumber + CERT_FILE_EXTENSION;
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("load certificate:" + cert_file_name);
+ }
+ cert = X509Cert.initByFilePath(cert_file_name);
+
+ if (cert == null)
+ {
+ logger_.info("The certificate '" + issuer + "', '" + serialNumber + "' wasn't found in the local certificate store - connecting to LDAP.");
+
+ // the certificate wasn't found in the local store
+ // - load it from the LDAP server.
+ String normalized_issuer = normalizer_.normalize(issuer);
+
+ byte[] cert_data = loadCertificateFromLDAP(serialNumber, normalized_issuer);
+ if (cert_data == null)
+ {
+ logger_.info("The certificate '" + issuer + "', '" + serialNumber + "' wasn't found on the LDAP server either.");
+
+ return null;
+ }
+
+ storeNewCertificateInLocalStore(cert_data);
+
+ // load the local cert
+ cert = X509Cert.initByFilePath(cert_file_name);
+
+ if (cert == null)
+ {
+ logger_.debug("The certificate should be loaded here, but is null - something's wrong.");
+ }
+ }
+ }
+ return cert;
+ }
+
+ /**
+ * This is an internal counter for added certificates.
+ */
+ protected static int new_cert_num = 0;
+
+ /**
+ * Writes the certificate data to a file and stores the file in the local
+ * certificate store.
+ *
+ * @param cert_data
+ * The binary certificate data.
+ */
+ public void storeNewCertificateInLocalStore(byte[] cert_data)
+ {
+ // write the loaded certificate to the add directory
+ String cert_add_path = certPath_ + CERT_ADD_DIR;
+ File cert_add_dir = new File(cert_add_path);
+ if (!cert_add_dir.exists())
+ {
+ cert_add_dir.mkdirs();
+ }
+ File save_file = new File(cert_add_dir, "newcert_" + new_cert_num + ".der");
+ new_cert_num++;
+ try
+ {
+ FileOutputStream fos = new FileOutputStream(save_file);
+ fos.write(cert_data);
+ fos.close();
+ }
+ catch (IOException e)
+ {
+ e.printStackTrace();
+ return;
+ }
+
+ // add the new certificate to the local store
+ addNewCertificates();
+ }
+
+ /**
+ * Connects to the LDAP server to look for the certificate.
+ *
+ * @param serialNumber
+ * The serial number String of the certificate being sought. E.g.
+ * "123455676744123432".
+ * @param issuer
+ * The issuer String of the certificate being sought.
+ *
+ * @return Returns the DER certificate file as can be stored in the local
+ * repository. Returns null, if the document wasn't found on the
+ * server.
+ */
+ protected byte[] loadCertificateFromLDAP(String serialNumber, String issuer)
+ {
+ String ldap_server_url = null;
+ try
+ {
+ ldap_server_url = settings_.getSetting("ldap.url");
+ }
+ catch (SettingNotFoundException e)
+ {
+ e.printStackTrace();
+ logger_.info("LDAP server url setting not found.");
+ return null;
+ }
+ logger_.debug("LDAP server url = " + ldap_server_url);
+
+ // TODO connect to LDAP using the EGIZ API.
+ DummyLDAPAPI api = new DummyLDAPAPI(ldap_server_url);
+ byte[] cert = api.loadCertificateFromLDAP(serialNumber, issuer);
+
+ return cert;
+ }
+
+ /**
+ * This method stores a X509v3 certificate to the filesystem. The reference to
+ * the stored certificate is build by the serialNumber and the issuer string.
+ * The issuer string is normalized because if getting this value from a pdf
+ * extraction it can be splited into more sections or necessary spaces are
+ * removed. The real issuer value is stored in the certificates meta file. The
+ * certficate is devided into two files: certificate.der (the binary value)
+ * and the meta information used in SignatureObjects as well in
+ * SignatureImages of a signed pdf-document. The storing path of the
+ * certificate is build by:
+ * <ol>
+ * <li>normalize the issuer string</li>
+ * <li>reduce all white spaces in the normalized issuer string</li>
+ * <li>build a hash value of this reduced string</li>
+ * <li>code this hash value as base64 value</li>
+ * <li>add the base64 normalized issuer hash value to the certificate base
+ * store path</li>
+ * <li>add the serialNumber to the cert path</li>
+ * <li>add the <code>.der</code> extension to get the certificate binary</li>
+ * <li>add the <code>.txt</code> extension to get the meta information of
+ * the certificate</li>
+ * </ol>
+ *
+ * The certificate meta file is build by the base64 coded issuer string and
+ * the cert digest value devided by the <code>@</code> char.
+ *
+ * @param serialNumber
+ * the file name of the certificate .der|.txt
+ * @param issuer
+ * the issuer string for the file path value of the certificate and
+ * for metainformation
+ * @param x509Certificate
+ * the x509v3 binary string
+ * @param x509Digest
+ * the digest value of the given x509Certificate
+ * @return true the certificate is stored completely, false otherwise
+ */
+ private boolean storeCertificate(String serialNumber, String issuer,
+ String x509Certificate, String x509Digest)
+ {
+ boolean store_complete = false;
+ if (issuer != null && serialNumber != null)
+ {
+ // String issuer_b64 = CodingHelper.encodeBase64(issuer.getBytes());
+ String iss_hash = getIssuerFileHash(issuer);
+ File cert_path_dir = new File(certPath_);
+ if (!cert_path_dir.exists())
+ {
+ cert_path_dir.mkdir();
+ }
+ String cert_store_path = certPath_ + iss_hash;
+ File cert_store_dir = new File(cert_store_path);
+ if (!cert_store_dir.exists())
+ {
+ cert_store_dir.mkdir();
+ }
+ if (cert_store_dir.isDirectory())
+ {
+ String cert_file_name = cert_store_path + FILE_SEP + serialNumber + CERT_FILE_EXTENSION;
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("store certificate:" + cert_file_name);
+ }
+ boolean store_cert_file = FileHelper.writeToFile(cert_file_name, x509Certificate);
+ store_complete = store_cert_file;// && store_cert_meta;
+ }
+ }
+ return store_complete;
+ }
+
+ /**
+ * @return Returns the AbstractTable.
+ * @see at.knowcenter.wag.egov.egiz.table.Table
+ */
+ public Table getAbstractTable()
+ {
+ if (sigTable_ == null)
+ {
+ sigTable_ = createSigTable(SignatureTypes.MAIN_TABLE);
+ }
+ return sigTable_;
+ }
+
+ /**
+ * This method read the style definitions from the settings file.
+ *
+ * @param styleKey
+ * the key to read the style definitions
+ * @return the defined style informations
+ * @see at.knowcenter.wag.egov.egiz.table.Style
+ */
+ private Style readStyle(String styleKey)
+ {
+ ArrayList styles = settings_.getKeys(styleKey);
+ Style style = new Style();
+ for (int style_idx = 0; style_idx < styles.size(); style_idx++)
+ {
+ String style_id = (String) styles.get(style_idx);
+ String style_val = settings_.getSetting(styleKey + "." + style_id, null);
+ style.setStyle(style_id, style_val);
+ }
+ return style;
+ }
+
+ /**
+ * This method creates an abstract signature table object. It takes all keys
+ * and values set by the signature object to create the corresponding abstract
+ * table object. The table definition is read from the settings file.
+ *
+ * @param tableKey
+ * is the name of the table definition in the settings file
+ * @return a new abstract signature table
+ * @see at.knowcenter.wag.egov.egiz.table.Style
+ * @see at.knowcenter.wag.egov.egiz.table.Table
+ * @see at.knowcenter.wag.egov.egiz.table.Entry
+ */
+ private Table createSigTable(String tableKey)
+ {
+ String table_key_prefix = SignatureTypes.SIG_OBJ + getSignationType() + "." + SignatureTypes.TABLE;
+ String table_key = table_key_prefix + tableKey;
+ // String caption_prefix = SignatureTypes.SIG_OBJ + getSignationType() +
+ // ".key.";
+ // String value_prefix = SignatureTypes.SIG_OBJ + getSignationType() +
+ // ".value.";
+ // ArrayList table_def_keys = settings_.getKeys(table_key);
+ Vector table_def_keys = settings_.getSettingKeys(table_key);
+ if (table_def_keys == null)
+ {
+ return null;
+ }
+ Table sig_table = new Table(tableKey);
+ boolean found_style = false;
+ for (int table_key_idx = table_def_keys.size() - 1; table_key_idx >= 0; table_key_idx--)
+ {
+ String table_def = (String) table_def_keys.get(table_key_idx);
+ int dot_idx = (table_def.indexOf(".") > 0 ? table_def.indexOf(".") : table_def.length());
+ table_def = table_def.substring(0, dot_idx);
+ String table_def_keys_prefix = table_key + "." + table_def;
+ String table_def_string = settings_.getSetting(table_def_keys_prefix, null);
+ if (table_def.matches("\\D*"))
+ {
+ // if the table key is not a number (row number index)
+ if (SignatureTypes.COLS_WITH.equals(table_def))
+ {
+ String[] cols_s = table_def_string.split(" ");
+ float[] cols_f = new float[cols_s.length];
+ for (int i = 0; i < cols_s.length; i++)
+ {
+ cols_f[i] = Float.parseFloat(cols_s[i]);
+ }
+ sig_table.setColsRelativeWith(cols_f);
+ }
+ if (SignatureTypes.STYLE.equals(table_def) && !found_style)
+ {
+ Style style = readStyle(table_def_keys_prefix);
+ sig_table.setStyle(style);
+ found_style = true;
+ }
+ continue;
+ }
+ if (table_def_string != null)
+ {
+ // analyse the row definition
+ String[] elems = table_def_string.split("\\|");
+ ArrayList row = new ArrayList();
+ for (int elem_idx = 0; elem_idx < elems.length; elem_idx++)
+ {
+ String elem = elems[elem_idx];
+ String[] key_type = elem.split("-");
+ if (key_type.length < 2)
+ {
+ return null;
+ }
+ String key = key_type[0];
+ String type = key_type[1];
+ if (SignatureTypes.TYPE_TABLE.equals(key))
+ {
+ // add a table entry
+ Table table = createSigTable(type);
+ if (table != null)
+ {
+ Entry entry = new Entry(Entry.TYPE_TABLE, table, key);
+ row.add(entry);
+ }
+ }
+ if (SignatureTypes.TYPE_IMAGE.equals(type))
+ {
+ // add an image entry
+ String value = getSigValue(key);
+ if (value != null)
+ {
+ Entry entry = new Entry(Entry.TYPE_IMAGE, value, key);
+ entry.setStyle(defaultImageStyle_);
+ row.add(entry);
+ }
+ }
+ if (SignatureTypes.TYPE_VALUE.equals(type))
+ {
+ // add a single value entry
+ String value = getSigValue(key);
+ Entry entry = new Entry(Entry.TYPE_VALUE, value, key);
+ if (entry != null)
+ {
+ entry.setColSpan(2);
+ entry.setStyle(defaultCaptionStyle_);
+ row.add(entry);
+ }
+ }
+ if ((SignatureTypes.TYPE_VALUE + SignatureTypes.TYPE_CAPTION).equals(type) || (SignatureTypes.TYPE_CAPTION + SignatureTypes.TYPE_VALUE).equals(type))
+ {
+ // add a caption value pair
+ String caption = getSigCaption(key);
+ String value = getSigValue(key);
+ if (value != null)
+ {
+ Entry c_entry = new Entry(Entry.TYPE_CAPTION, caption, key);
+ // c_entry.setNoWrap(true);
+ c_entry.setStyle(defaultCaptionStyle_);
+
+ Entry v_entry = new Entry(Entry.TYPE_VALUE, value, key);
+ v_entry.setStyle(defaultValueStyle_);
+ if (c_entry != null && v_entry != null)
+ {
+ row.add(c_entry);
+ row.add(v_entry);
+ }
+ }
+ }
+ }
+ sig_table.addRow(table_def, row);
+ }
+ }
+
+ return sig_table;
+ }
+
+ /**
+ * This method inits the signature object by the given type. It loads the
+ * configured values and captions from the config.properties file.
+ */
+ public void initByType() throws SignatureTypesException
+ {
+ if (sigType_ == null)
+ {
+ sigType_ = getDefaultSigType();
+ }
+ SignatureTypes sig_types = SignatureTypes.getInstance();
+ signatureDefinition_ = sig_types.getSignatureTypeDefinition(sigType_);
+ Map key_cap_map = signatureDefinition_.getKeyCaptionMap();
+ if (key_cap_map != null)
+ {
+ Iterator key_cap = key_cap_map.entrySet().iterator();
+ while (key_cap.hasNext())
+ {
+ Map.Entry entry = (Map.Entry) key_cap.next();
+ String key = (String) entry.getKey();
+ String caption = (String) entry.getValue();
+ SignatureEntry sig_entry = null;
+ if (sigEntries_.containsKey(key))
+ {
+ sig_entry = (SignatureEntry) sigEntries_.get(key);
+ }
+ else
+ {
+ sig_entry = new SignatureEntry(key);
+ sigEntries_.put(key, sig_entry);
+ }
+ sig_entry.setCaption(caption);
+ }
+ }
+
+ Map key_val_map = signatureDefinition_.getKeyValueMap();
+ if (key_val_map != null)
+ {
+ Set key_val_set = key_val_map.entrySet();
+ Iterator key_val = key_val_set.iterator();
+ while (key_val.hasNext())
+ {
+ Map.Entry entry = (Map.Entry) key_val.next();
+ String key = (String) entry.getKey();
+ String value = (String) entry.getValue();
+ if (SignatureTypes.SIG_NORM.equals(key))
+ {
+ try
+ {
+ normalizer_.setVersion(value);
+ }
+ catch (NormalizeException e)
+ {
+ throw new SignatureTypesException("Can not set normalizer Version:" + value);
+ }
+ }
+ // value = new String(CodingHelper.encodeUTF8(value));
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("key:" + key + " value:" + value);
+ }
+ setSigValue(key, value);
+ }
+ }
+ }
+
+ /**
+ * This method returns a signature entry object.
+ *
+ * @param key
+ * the corresponding key
+ * @return the signature entry object of the given key, null if the key does
+ * not exist
+ */
+ public SignatureEntry getSigEntry(String key)
+ {
+ return (SignatureEntry) sigEntries_.get(key);
+ }
+
+ /**
+ * This method is a helper function to remove all white spaces from a text.
+ *
+ * @param text
+ * the white spaces should remove from
+ * @return a text without white spaces
+ */
+ private static String removeAllWhiteSpaces(String text)
+ {
+ return text.replaceAll("\\s", "");
+ }
+
+ public SignatureTypeDefinition getSignatureTypeDefinition()
+ {
+ return this.signatureDefinition_;
+ }
+
+ /**
+ *
+ * @param placeholder
+ * @return Returns the list of SignatureFieldDefinitions that's values in the
+ * SignatureObject have been filled out with placeholders.
+ */
+ public List fillValues(final char placeholder, boolean has_SIG_ID)
+ {
+ List variable_fields = new ArrayList();
+
+ List field_definitions = this.signatureDefinition_.getFieldDefinitions();
+ Iterator it = field_definitions.iterator();
+ while (it.hasNext())
+ {
+ SignatureFieldDefinition sfd = (SignatureFieldDefinition) it.next();
+ String value_string = null;
+ if (sfd.placeholder_length > 0)
+ {
+ if (sfd.field_name.equals(SignatureTypes.SIG_ID) && has_SIG_ID == false)
+ {
+ setValueBruteForce(SignatureTypes.SIG_ID, null);
+ continue;
+ }
+
+ char[] placeholder_chars = new char[sfd.placeholder_length];
+ for (int i = 0; i < placeholder_chars.length; i++)
+ {
+ placeholder_chars[i] = placeholder;
+ }
+ value_string = new String(placeholder_chars);
+
+ variable_fields.add(sfd);
+
+ setSigValue(sfd.field_name, value_string);
+ }
+ }
+
+ return variable_fields;
+ }
+
+ /**
+ * Returns the raw signature response XML string as set by the signing
+ * Connector.
+ *
+ * @return Returns the XML response String.
+ */
+ public String getRawSignatureResponse()
+ {
+ return this.raw_signature_response;
+ }
+
+ /**
+ * Sets the raw signature response XML string.
+ *
+ * <p>
+ * This should be used by the Connector to pass the response String to the
+ * signer.
+ * </p>
+ *
+ * @param raw_response_string
+ * The new raw signature response string.
+ */
+ public void setRawSignatureResponse(String raw_response_string)
+ {
+ this.raw_signature_response = raw_response_string;
+ }
+
+ /**
+ * The toString method, used for tests or debugging.
+ */
+ public String toString()
+ {
+ String strg = "";
+ Iterator it = sigEntries_.values().iterator();
+ while (it.hasNext())
+ {
+ SignatureEntry sig_entry = (SignatureEntry) it.next();
+ String key = sig_entry.getKey();
+ String caption = sig_entry.getCaption();
+ String value = sig_entry.getValue();
+ strg += key + "=" + caption + ":" + value + "\n";
+ }
+ strg += "Signation Type:" + getSignationType() + "\n";
+ return strg;
+ }
+
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureResponse.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureResponse.java
new file mode 100644
index 0000000..f576e65
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureResponse.java
@@ -0,0 +1,470 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureResponse.java,v 1.4 2006/08/03 07:43:04 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.PropertyTree;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingNotFoundException;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+
+/**
+ * The response of a verification.
+ *
+ * @author wlackner
+ */
+public class SignatureResponse
+{
+ /**
+ * The siganture response config key
+ */
+ private static String SIG_RESP_KEY = "signature.response.";
+
+ /**
+ * Default response message
+ */
+ private static String SIG_RESP_DEFAULT_INFO = "Es ist leider keine nähere Information verfügbar:";
+
+ /**
+ * Response value for x509SubjectName_
+ */
+ private String x509SubjectName_ = null;
+
+ /**
+ * Response value for x509IssuerName
+ */
+ private String x509IssuerName = null;
+
+ /**
+ * Response value for x509SerialNumber
+ */
+ private String x509SerialNumber = null;
+
+ /**
+ * Response value for signatureCheckCode_
+ */
+ private String signatureCheckCode_ = null;
+
+ /**
+ * Response value for signatureCheckInfo_
+ */
+ private String signatureCheckInfo_ = null;
+
+ /**
+ * Response value for signatureManifestCheckCode_
+ */
+ private String signatureManifestCheckCode_ = null;
+
+ /**
+ * Response value for signatureManifestCheckInfo_
+ */
+ private String signatureManifestCheckInfo_ = null;
+
+ /**
+ * Response value for certificateCheckCode_
+ */
+ private String certificateCheckCode_ = null;
+
+ /**
+ * Response value for certificateCheckInfo_
+ */
+ private String certificateCheckInfo_ = null;
+
+ /**
+ * The X.509 certificated parsed from the response string.
+ */
+ protected X509Cert certificate_ = null;
+
+ // /**
+ // * Flag the marks that the response is an error response
+ // */
+ // private boolean isError_ = false;
+ //
+ // /**
+ // * The error code of an external application
+ // */
+ // private String errorCode_ = null;
+
+ /**
+ * The SettingsReader instance
+ */
+ private SettingsReader settings_ = null;
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(SignatureResponse.class);
+
+ /**
+ *
+ *
+ */
+ public SignatureResponse()
+ {
+ try
+ {
+ loadSettings();
+ }
+ catch (SignatureException e)
+ {
+ logger_.warn(e.getMessage());
+ }
+ }
+
+ /**
+ * load the inital signature settings
+ *
+ * @throws SignatureException
+ * @see SettingsReader
+ */
+ private void loadSettings() throws SignatureException
+ {
+ if (settings_ == null)
+ {
+ try
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ catch (SettingsException e)
+ {
+ String log_message = "Can not load signature settings. Cause:\n" + e.getMessage();
+ logger_.error(log_message);
+ throw new SignatureException(101, log_message, e);
+ }
+ }
+ }
+
+ /**
+ * @return Returns the certificateCheckCode.
+ */
+ public String getCertificateCheckCode()
+ {
+ return certificateCheckCode_;
+ }
+
+ /**
+ * @param certificateCheckCode
+ * The certificateCheckCode to set.
+ */
+ public void setCertificateCheckCode(String certificateCheckCode)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setCertificateCheckCode:" + certificateCheckCode);
+ }
+ certificateCheckCode_ = certificateCheckCode;
+ }
+
+ /**
+ * @return Returns the signatureCheckCode.
+ */
+ public String getSignatureCheckCode()
+ {
+ return signatureCheckCode_;
+ }
+
+ /**
+ * @param signatureCheckCode
+ * The signatureCheckCode to set.
+ */
+ public void setSignatureCheckCode(String signatureCheckCode)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setSignatureCheckCode:" + signatureCheckCode);
+ }
+ signatureCheckCode_ = signatureCheckCode;
+ }
+
+ /**
+ * @return Returns the signatureManifestCheckCode.
+ */
+ public String getSignatureManifestCheckCode()
+ {
+ return signatureManifestCheckCode_;
+ }
+
+ /**
+ * @param signatureManifestCheckCode
+ * The signatureManifestCheckCode to set.
+ */
+ public void setSignatureManifestCheckCode(String signatureManifestCheckCode)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setSignatureManifestCheckCode:" + signatureManifestCheckCode);
+ }
+ signatureManifestCheckCode_ = signatureManifestCheckCode;
+ }
+
+ /**
+ * @return Returns the x509IssuerName.
+ */
+ public String getX509IssuerName()
+ {
+ return x509IssuerName;
+ }
+
+ /**
+ * @param issuerName
+ * The x509IssuerName to set.
+ */
+ public void setX509IssuerName(String issuerName)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setX509IssuerName:" + issuerName);
+ }
+ x509IssuerName = issuerName;
+ }
+
+ /**
+ * @return Returns the x509SerialNumber.
+ */
+ public String getX509SerialNumber()
+ {
+ return x509SerialNumber;
+ }
+
+ /**
+ * @param serialNumber
+ * The x509SerialNumber to set.
+ */
+ public void setX509SerialNumber(String serialNumber)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setX509SerialNumber:" + serialNumber);
+ }
+ x509SerialNumber = serialNumber;
+ }
+
+ /**
+ * @return Returns the x509SubjectName.
+ */
+ public String getX509SubjectName()
+ {
+ return x509SubjectName_;
+ }
+
+ /**
+ * @param subjectName
+ * The x509SubjectName to set.
+ */
+ public void setX509SubjectName(String subjectName)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setX509SubjectName:" + subjectName);
+ }
+ x509SubjectName_ = subjectName;
+ }
+
+ /**
+ * @return Returns the certificateCheckInfo.
+ */
+ public String getCertificateCheckInfo()
+ {
+ if (certificateCheckInfo_ == null)
+ {
+ if (settings_ != null)
+ {
+ certificateCheckInfo_ = settings_.getValueFromKey(SIG_RESP_KEY + "certificateCheckInfo." + getCertificateCheckCode());
+ }
+ }
+ if (certificateCheckInfo_ == null)
+ {
+ certificateCheckInfo_ = SIG_RESP_DEFAULT_INFO + getCertificateCheckCode();
+ }
+ return certificateCheckInfo_;
+ }
+
+ /**
+ * @param certificateCheckInfo
+ * The certificateCheckInfo to set.
+ */
+ public void setCertificateCheckInfo(String certificateCheckInfo)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setCertificateCheckInfo:" + certificateCheckInfo);
+ }
+ certificateCheckInfo_ = certificateCheckInfo;
+ }
+
+ /**
+ * @return Returns the signatureCheckInfo.
+ */
+ public String getSignatureCheckInfo()
+ {
+ if (signatureCheckInfo_ == null)
+ {
+ if (settings_ != null)
+ {
+ signatureCheckInfo_ = settings_.getValueFromKey(SIG_RESP_KEY + "signatureCheckInfo." + getSignatureCheckCode());
+ }
+ }
+ if (signatureCheckInfo_ == null)
+ {
+ signatureCheckInfo_ = SIG_RESP_DEFAULT_INFO + getSignatureCheckCode();
+ }
+ return signatureCheckInfo_;
+ }
+
+ /**
+ * @param signatureCheckInfo
+ * The signatureCheckInfo to set.
+ */
+ public void setSignatureCheckInfo(String signatureCheckInfo)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setSignatureCheckInfo:" + signatureCheckInfo);
+ }
+ signatureCheckInfo_ = signatureCheckInfo;
+ }
+
+ /**
+ * @return Returns the signatureManifestCheckInfo.
+ */
+ public String getSignatureManifestCheckInfo()
+ {
+ if (signatureManifestCheckInfo_ == null)
+ {
+ if (settings_ != null)
+ {
+ signatureManifestCheckInfo_ = settings_.getValueFromKey(SIG_RESP_KEY + "signatureManifestCheckInfo." + getSignatureManifestCheckCode());
+ }
+ }
+ if (signatureManifestCheckInfo_ == null)
+ {
+ signatureManifestCheckInfo_ = SIG_RESP_DEFAULT_INFO + getSignatureManifestCheckCode();
+ }
+ return signatureManifestCheckInfo_;
+ }
+
+ /**
+ * @param signatureManifestCheckInfo
+ * The signatureManifestCheckInfo to set.
+ */
+ public void setSignatureManifestCheckInfo(String signatureManifestCheckInfo)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("setSignatureManifestCheckInfo:" + signatureManifestCheckInfo);
+ }
+ signatureManifestCheckInfo_ = signatureManifestCheckInfo;
+ }
+
+ /**
+ * Returns the X.509 certificate of this response.
+ *
+ * @return Returns the X.509 certificate of this response.
+ */
+ public X509Cert getCertificate()
+ {
+ return certificate_;
+ }
+
+ /**
+ * Sets the X.509 certificate of this response.
+ *
+ * @param certificate
+ * The X.509 certificate to be set.
+ */
+ public void setCertificate(X509Cert certificate)
+ {
+ this.certificate_ = certificate;
+ }
+
+ /**
+ * Returns a list of Strings each stating one public property of the
+ * certificate.
+ *
+ * <p>
+ * Such public properties are certificate extensions each being assigned an
+ * own OID. For example the public property "Verwaltungseigenschaft" has the
+ * OID "1.2.40.0.10.1.1.1".
+ * </p>
+ * <p>
+ * This methods reads out the list of possible properties from the config file
+ * and compares these to the extensions defined on the certificate. If they
+ * match, a String containing useful information about the property is added
+ * to the list returned.
+ * </p>
+ *
+ * @return Returns the list of Strings representing the public properties of
+ * this certificate, if any.
+ * @throws SettingNotFoundException
+ */
+ public List getPublicProperties() throws SettingNotFoundException
+ {
+ List props = new ArrayList();
+
+ SettingsReader settings = this.settings_;
+
+ String root_oid = settings.getSetting("oid.root");
+
+ PropertyTree oids = settings.getPTree().getSubTree("oid");
+
+ Set non_critial_oids = this.certificate_.getX509Certificate().getNonCriticalExtensionOIDs();
+ Iterator ext_it = non_critial_oids.iterator();
+ while (ext_it.hasNext())
+ {
+ String oid = (String) ext_it.next();
+
+ if (oid.startsWith(root_oid))
+ {
+ String key = oid.replaceAll("\\.", "_");
+
+ String value = oids.getLastValue(key);
+ if (value == null)
+ {
+ value = oid;
+ }
+
+ props.add(value);
+ }
+ }
+
+ return props;
+ }
+
+ /**
+ * The toString method
+ */
+ public String toString()
+ {
+ String str = "";
+ str += "\nSignator:" + getX509SubjectName();
+ str += "\nAusteller:" + getX509IssuerName();
+ str += "\nSeriennummer:" + getX509SerialNumber();
+ str += "\nZertifikat-Code:" + getCertificateCheckCode() + "=" + getCertificateCheckInfo();
+ str += "\nSignatur-Check-Code:" + getSignatureCheckCode() + "=" + getSignatureCheckInfo();
+ str += "\nManifest-Check-Code:" + getSignatureManifestCheckCode() + "=" + getSignatureManifestCheckInfo();
+ return str;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureSeparator.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureSeparator.java
new file mode 100644
index 0000000..3a210fa
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureSeparator.java
@@ -0,0 +1,139 @@
+/*
+ * <copyright>
+ * Copyright (c) 2006 by Know-Center, Graz, Austria
+ * </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF THE
+ * SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
+ * OR NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES
+ * SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING
+ * THIS SOFTWARE OR ITS DERIVATIVES.
+ *
+ * $Id: SignatureSeparator.java,v 1.4 2006/10/31 08:18:56 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.util.List;
+import java.util.Stack;
+
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+
+/**
+ * This class separates all signature blocks in a raw text.
+ */
+public class SignatureSeparator {
+ /**
+ * The signature block stack. On top of the stack is the first signature block that can be
+ * extracted. First means nearest to the document text.
+ */
+ private Stack signatureBlocks_ = null;
+ /**
+ * A list of signature type definitions.
+ */
+ private List signatureTypes_ = null;
+ /**
+ * Indicator that shows that a raw text is signated
+ */
+ private boolean hasSignatureBlock_ = false;
+
+ /**
+ * The empty constructor. It loads all signature type infos to extract the signature block from
+ * the raw text.
+ *
+ * @throws SignatureTypesException
+ */
+ public SignatureSeparator() throws SignatureTypesException {
+ SignatureTypes sig_types = SignatureTypes.getInstance();
+ signatureTypes_ = sig_types.getSignatureTypeDefinitions();
+ }
+
+ /**
+ * This method takes a raw text as input and trys to separate all signature blocks. It returns
+ * true if a signature block is found.
+ *
+ * @param rawText
+ * @return true if a signature block is found false otherwise
+ */
+ public boolean separateBlock(String rawText) {
+ signatureBlocks_ = new Stack();
+ hasSignatureBlock_ = separateBlock(rawText, rawText.length());
+ return hasSignatureBlock_;
+ }
+
+ /**
+ * This method calls itself rekursively while signature blocks can be extracted. If a signature
+ * block is found (search from the bottom of the raw text) the raw text would be reduced by the
+ * length of the found signature block text.
+ *
+ * @param rawText the text to be separated
+ * @param endIndex the index to cut the tail from the raw text
+ * @return true if a signature block is found false otherwise
+ */
+ private boolean separateBlock(String rawText, int endIndex) {
+ boolean found = false;
+ boolean can_separate = true;
+ while (can_separate) {
+ SignatureBlock sig_block = new SignatureBlock(signatureTypes_);
+ String raw_text = rawText.substring(0, endIndex);
+ can_separate = sig_block.separateBlockFromRawText(raw_text, true);
+ if (can_separate) {
+ signatureBlocks_.push(sig_block);
+ endIndex = sig_block.getStartIndex();
+ found = true;
+ }
+ }
+ return found;
+ }
+
+ /**
+ * This method returns the start index of the first signature block. It is used to separate the
+ * real document text from the signature block texts.
+ *
+ * @return the start index of the first signature block
+ */
+ public int getStartIndex() {
+ int start_index = -1;
+ if (signatureBlocks_ != null && signatureBlocks_.size() > 0) {
+ SignatureBlock sig_block = (SignatureBlock) signatureBlocks_.peek();
+ return sig_block.getStartIndex();
+ }
+ return start_index;
+ }
+
+ /**
+ * @return the first found signature object in the given raw text or null if the raw text does not
+ * contain any signature objects
+ */
+ public SignatureObject getFirstSignatureObject() {
+ if (signatureBlocks_ != null && signatureBlocks_.size() > 0) {
+ SignatureBlock sig_block = (SignatureBlock) signatureBlocks_.peek();
+ try {
+ return sig_block.getSignatureObject();
+ } catch (SignatureException e) {
+ return null;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * @return all separated signature blocks as stack, first is on top
+ */
+ public Stack getSignatureBlocks() {
+ return signatureBlocks_;
+ }
+
+ /**
+ * @return true if a signature block is found false otherwise
+ */
+ public boolean hasSignatureBlock() {
+ return hasSignatureBlock_;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypeDefinition.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypeDefinition.java
new file mode 100644
index 0000000..4b14019
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypeDefinition.java
@@ -0,0 +1,423 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureTypeDefinition.java,v 1.3 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+
+public class SignatureTypeDefinition implements Serializable
+{
+
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = 1327407307346061147L;
+
+ /**
+ * The type of this definition
+ */
+ private String type_ = null;
+
+ /**
+ * A map of all key to caption tupls.
+ */
+ private Map keyCaptionMap_ = new HashMap();
+
+ /**
+ * A map of all key to value tupls.
+ */
+ private Map keyValueMap_ = new HashMap();
+
+ /**
+ * A list of sorted keys
+ */
+ private Vector sortedKeys_ = null;
+
+ /**
+ * A list of sorted captions
+ */
+ private Vector sortedCaptions_ = null;
+
+ /**
+ * A revert of sorted keys
+ */
+ private Vector revertSortedKeys_ = new Vector();
+
+ /**
+ * A revert list of sorted captions
+ */
+ private Vector revertSortedCaptions_ = new Vector();
+
+ /**
+ * The settings reader reference
+ */
+ private SettingsReader settings_ = null;
+
+ /**
+ * The constructor of the signature type definition. It reads the configured
+ * table definition of the signature block and load the type definition of a
+ * given type.
+ *
+ * @param settings
+ * a SettingsReader instance
+ * @param type
+ * the signature type to load
+ * @throws SignatureException
+ * @see SettingsReader
+ */
+ public SignatureTypeDefinition(SettingsReader settings, String type) throws SignatureException
+ {
+ settings_ = settings;
+ type_ = type;
+ readSigTable(SignatureTypes.MAIN_TABLE);
+ loadTypeDefinition();
+ readFieldDefinitions();
+ }
+
+ /**
+ * Load the configured signature type definitions. It reads all key-captions
+ * tupls that are used in the signature table. It also reads all key-value
+ * tupls.
+ *
+ * @throws SignatureException
+ */
+ private void loadTypeDefinition() throws SignatureException
+ {
+ if (sortedKeys_ == null)
+ {
+ sortKeys();
+ }
+
+ String key_prefix = SignatureTypes.SIG_OBJ + type_ + ".key";
+ ArrayList keys = settings_.getKeys(key_prefix);
+ if (keys == null)
+ {
+ SignatureException se = new SignatureException(100, "There is no key defined for type:" + type_);
+ ;
+ throw se;
+ }
+ for (int key_idx = 0; key_idx < keys.size(); key_idx++)
+ {
+ String sig_key = (String) keys.get(key_idx);
+ String sig_key_val = settings_.getValueFromKey(key_prefix + "." + sig_key);
+ if (sortedKeys_.contains(sig_key))
+ {
+ keyCaptionMap_.put(sig_key, sig_key_val);
+ }
+ }
+ String value_prefix = SignatureTypes.SIG_OBJ + type_ + ".value";
+ ArrayList values = settings_.getKeys(value_prefix);
+ if (values != null)
+ {
+ for (int key_idx = 0; key_idx < values.size(); key_idx++)
+ {
+ String val_key = (String) values.get(key_idx);
+ String val_key_val = settings_.getValueFromKey(value_prefix + "." + val_key);
+ keyValueMap_.put(val_key, val_key_val);
+ }
+ }
+ }
+
+ /**
+ * This method reads the table definition of singature type. It takes care
+ * about the linearization of the defined key-value pairs or sub tables. The
+ * linearisation is done reading a table from left to right and top to bottom.
+ * A sub table is alwais a normal cell element in the linearisation prozess.
+ * If a sub table exists therefore the linearisation of the subtable is taken
+ * es cell element in the parent table. t This method stores a revert sorted
+ * linearisation list of used keys in the table. This method is called
+ * recursivley if defined nested tables.
+ *
+ * @param tableKey
+ * the name of the table definition
+ */
+ private void readSigTable(String tableKey)
+ {
+ // System.err.println("read table:" + type_ + "." + tableKey);
+ String table_key_prefix = SignatureTypes.SIG_OBJ + type_ + "." + SignatureTypes.TABLE;
+ String table_key = table_key_prefix + tableKey;
+ String key_prefix = SignatureTypes.SIG_OBJ + type_ + ".key.";
+
+ // ArrayList table_def_keys = settings_.getKeys(table_key);
+ Vector table_def_keys = settings_.getSettingKeys(table_key);
+ if (table_def_keys != null)
+ {
+ for (int table_key_idx = 0; table_key_idx < table_def_keys.size(); table_key_idx++)
+ {
+ String table_row_id = (String) table_def_keys.get(table_key_idx);
+ String table_def_keys_name = table_key + "." + table_row_id;
+ String table_def_string = settings_.getValueFromKey(table_def_keys_name);
+ if (table_row_id.matches("\\D*"))
+ {
+ continue;
+ }
+ if (table_def_string != null)
+ {
+ // analyse the row definition
+ String[] elems = table_def_string.split("\\|");
+ // ArrayList row = new ArrayList();
+ int elem_idx = elems.length;
+ while (elem_idx > 0)
+ {
+ elem_idx--;
+ String elem = elems[elem_idx];
+ String[] key_type = elem.split("-");
+ if (key_type.length < 2)
+ {
+ return;
+ }
+ String key = key_type[0];
+ String type = key_type[1];
+ // System.err.println("key:" + type_ + "." + tableKey +
+ // "." + key + "=" + type);
+
+ if (SignatureTypes.TYPE_TABLE.equals(key))
+ {
+ // read sub table
+ readSigTable(type);
+ }
+ if (SignatureTypes.TYPE_IMAGE.equals(type))
+ {
+ // ignore images
+ }
+ if (SignatureTypes.TYPE_VALUE.equals(type))
+ {
+ String sig_key_val = settings_.getValueFromKey(key_prefix + key);
+ if (sig_key_val != null)
+ {
+ revertSortedKeys_.add(key);
+ revertSortedCaptions_.add(sig_key_val);
+ }
+ // ignore values without caption
+ }
+ if ((SignatureTypes.TYPE_VALUE + SignatureTypes.TYPE_CAPTION).equals(type) || (SignatureTypes.TYPE_CAPTION + SignatureTypes.TYPE_VALUE).equals(type))
+ {
+ String sig_key_val = settings_.getValueFromKey(key_prefix + key);
+ if (sig_key_val != null)
+ {
+ revertSortedKeys_.add(key);
+ revertSortedCaptions_.add(sig_key_val);
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @return Returns the keys.
+ */
+ public Map getKeyCaptionMap()
+ {
+ return keyCaptionMap_;
+ }
+
+ /**
+ * @return Returns the keyValueMap.
+ */
+ public Map getKeyValueMap()
+ {
+ return keyValueMap_;
+ }
+
+ /**
+ * Returns a caption to a given key
+ *
+ * @param key
+ * @return the caption or null if the key is not found
+ */
+ public String getCaptionFromKey(String key)
+ {
+ return (String) keyCaptionMap_.get(key);
+ }
+
+ /**
+ * Returns a value to given key
+ *
+ * @param key
+ * @return the value or null if the key is not found
+ */
+ public String getValueFromKey(String key)
+ {
+ return (String) keyValueMap_.get(key);
+ }
+
+ /**
+ * @return Returns the sortedKeys.
+ */
+ public Vector getSortedKeys()
+ {
+ if (sortedKeys_ == null)
+ {
+ sortKeys();
+ }
+ return sortedKeys_;
+ }
+
+ /**
+ * @return Returns the sortedCaptions.
+ */
+ public Vector getSortedCaptions()
+ {
+ if (sortedCaptions_ == null)
+ {
+ sortKeys();
+ }
+ return sortedCaptions_;
+ }
+
+ /**
+ * @return Returns the revertSortedCaptions.
+ */
+ public Vector getRevertSortedCaptions()
+ {
+ return revertSortedCaptions_;
+ }
+
+ /**
+ * @return Returns the revertSortedKeys.
+ */
+ public Vector getRevertSortedKeys()
+ {
+ return revertSortedKeys_;
+ }
+
+ /**
+ * This method sort the reverted sorted key-caption and key-value lists.
+ *
+ */
+ private void sortKeys()
+ {
+ // String key_prefix = SignatureTypes.SIG_OBJ + type_ + ".key.";
+ sortedKeys_ = new Vector(revertSortedKeys_.size());
+ sortedCaptions_ = new Vector(revertSortedCaptions_.size());
+ for (int key_idx = revertSortedKeys_.size() - 1; key_idx >= 0; key_idx--)
+ {
+ sortedKeys_.add(revertSortedKeys_.get(key_idx));
+ sortedCaptions_.add(revertSortedCaptions_.get(key_idx));
+ }
+ }
+
+ /**
+ * This method checks if a given key is defined.
+ *
+ * @param key
+ * to find
+ * @return true if the key is find false otherwise
+ */
+ public boolean contains(String key)
+ {
+ return (keyValueMap_.get(key) != null);
+ }
+
+ /**
+ * The standard toString method. Used for internal tests only.
+ */
+ public String toString()
+ {
+ String strg = this.type_ + "\n";
+ Vector sk = getSortedKeys();
+ Vector sc = getSortedCaptions();
+ for (int i = 0; i < sk.size(); i++)
+ {
+ strg += sk.get(i) + "=" + sc.get(i) + "\n";
+ }
+ return strg;
+ }
+
+ /**
+ * @return Returns the signature type string.
+ */
+ public String getType()
+ {
+ return type_;
+ }
+
+ /**
+ * @return Returns the signature type description.
+ */
+ public String getDescription()
+ {
+ String descr_key = SignatureTypes.SIG_OBJ + type_ + ".description";
+ return settings_.getValueFromKey(descr_key);
+ }
+
+ protected String getSettingsKeyBase()
+ {
+ return SignatureTypes.SIG_OBJ + type_;
+ }
+
+ /**
+ * Gets the field definition of the given Field.
+ *
+ * @param field_name
+ * The name of the field.
+ * @return Returns the field's definition.
+ */
+ public SignatureFieldDefinition readFieldDefinition(String field_name)
+ {
+ SignatureFieldDefinition sfd = new SignatureFieldDefinition();
+
+ sfd.field_name = field_name;
+ sfd.caption = this.settings_.getValueFromKey(getSettingsKeyBase() + ".key." + field_name);
+ sfd.value = this.settings_.getValueFromKey(getSettingsKeyBase() + type_ + ".value." + field_name);
+ sfd.placeholder_length = -1;
+ String phlen_str = this.settings_.getValueFromKey(getSettingsKeyBase() + ".phlength." + field_name);
+ if (phlen_str == null)
+ {
+ phlen_str = this.settings_.getValueFromKey("defaults.phlength." + field_name);
+ }
+ if (phlen_str != null)
+ {
+ sfd.placeholder_length = Integer.parseInt(phlen_str);
+ }
+
+ return sfd;
+ }
+
+ List field_definitions_ = null;
+
+ protected void readFieldDefinitions()
+ {
+ this.field_definitions_ = new ArrayList();
+ for (int i = 0; i < this.sortedKeys_.size(); i++)
+ {
+ String key = (String) this.sortedKeys_.get(i);
+ SignatureFieldDefinition sfd = readFieldDefinition(key);
+ //sfd.brev = SignatureTypes.ALL_SIG_BREV[i];
+ this.field_definitions_.add(sfd);
+ }
+ }
+
+ /**
+ * Returns the list of field definitions of this Signature profile.
+ * @return Returns the list of field definitions of this Signature profile.
+ */
+ public List getFieldDefinitions()
+ {
+ return this.field_definitions_;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypes.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypes.java
new file mode 100644
index 0000000..0350129
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/SignatureTypes.java
@@ -0,0 +1,462 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: SignatureTypes.java,v 1.5 2006/10/31 08:18:56 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.awt.Color;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Vector;
+
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+import at.knowcenter.wag.egov.egiz.table.Style;
+import at.knowcenter.wag.exactparser.ByteArrayUtils;
+
+public class SignatureTypes
+{
+
+ /**
+ * The settings key prefix for signature definitions. <code>"sig_obj."</code>
+ */
+ public static final String SIG_OBJ = "sig_obj.";
+
+ /**
+ * The settings key prefix for signature object types
+ */
+ public static final String TYPES = SIG_OBJ + "types";
+
+ /**
+ * The settings key prefix for the default signature object type
+ */
+ public static final String DEFAULT_TYPE = SIG_OBJ + "type.default";
+
+ /**
+ * The settings key postfix for the type description
+ */
+ public static final String SIG_DESCR = "description";
+
+ /**
+ * The state value activating an signature definition
+ */
+ private static final String STATE_ON = "on";
+
+ // /**
+ // * The state value de activating an signature definition
+ // */
+ // private static final String STATE_OFF = "off";
+
+ /**
+ * The settings key prefix for the signature table object definition
+ */
+ public static final String TABLE = "table.";
+
+ /**
+ * The settings key sub prefix getting the main table definition
+ */
+ public static final String MAIN_TABLE = "main";
+
+ /**
+ * The settings value refering to a table
+ */
+ public final static String TYPE_TABLE = "TABLE";
+
+ /**
+ * The settings value refering to an image
+ */
+ public final static String TYPE_IMAGE = "i";
+
+ /**
+ * The settings value refering to a text caption
+ */
+ public final static String TYPE_CAPTION = "c";
+
+ /**
+ * The settings value refering to a text value
+ */
+ public final static String TYPE_VALUE = "v";
+
+ /**
+ * The settings key sub prefix getting the width of columns for a table
+ * definition
+ */
+ public final static String COLS_WITH = "ColsWidth";
+
+ /**
+ * The settings key sub prefix getting the style definition
+ */
+ public final static String STYLE = "Style";
+
+ /**
+ * The default style definition for images.
+ */
+ private Style defaultImageStyle_ = new Style();
+
+ /**
+ * The default style definition for captions.
+ */
+ private Style defaultCaptionStyle_ = new Style();
+
+ /**
+ * The default style definition for values.
+ */
+ private Style defaultValueStyle_ = new Style();
+
+ /**
+ * Standard key get/set the singature name
+ */
+ public static final String SIG_NAME = "SIG_NAME";
+
+ /**
+ * Standard key get/set the signature date
+ */
+ public static final String SIG_DATE = "SIG_DATE";
+
+ /**
+ * Standard key get/set the signator issuer
+ */
+ public static final String SIG_ISSUER = "SIG_ISSUER";
+
+ /**
+ * Standard key get/set the siganture value
+ */
+ public static final String SIG_VALUE = "SIG_VALUE";
+
+ /**
+ * Standard key get/set the normalisation method used
+ */
+ public static final String SIG_NORM = "SIG_NORM";
+
+ /**
+ * Standard key get/set the signation id's used by BKU signated documents
+ */
+ public static final String SIG_ID = "SIG_ID";
+
+ /**
+ * The EGIZ Algorithm "Kennzeichnung".
+ */
+ public static final String SIG_KZ = "SIG_KZ";
+
+ /**
+ * Standard key get/set the reference to the signature label (image mark)
+ */
+ public static final String SIG_LABEL = "SIG_LABEL";
+
+ /**
+ * Standard key get/set the serial number of the signature
+ */
+ public static final String SIG_NUMBER = "SIG_NUMBER";
+
+ // public static final String SIG_TYPE = "SIG_TYPE";
+ /**
+ * Standard key get/set the signature meta informations
+ */
+ public static final String SIG_META = "SIG_META";
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(SignatureTypes.class);
+
+ // /**
+ // * The normalizer reference
+ // */
+ // private Normalizer normalizer_ = null;
+
+ /**
+ * The settings reader reference
+ */
+ private SettingsReader settings_ = null;
+
+ // /**
+ // * The reference to the settings property tree
+ // */
+ // private PropertyTree pTree_ = null;
+
+ // /**
+ // * The current signature type used reading and analysing the property tree
+ // */
+ // private String sigType_ = null;
+
+ // /**
+ // * List of all keys used in the current signature definition
+ // */
+ // private ArrayList sigKeys_ = null;
+
+ /**
+ * Array of required signature keys
+ */
+ // public static String[] REQUIRED_SIG_KEYS = new String[]{SIG_NAME, SIG_DATE,
+ // SIG_ISSUER, SIG_VALUE, SIG_NUMBER, SIG_ID};
+ public static String[] REQUIRED_SIG_KEYS = new String[] { SIG_DATE,
+ SIG_ISSUER, SIG_VALUE, SIG_NUMBER, SIG_ID };
+
+ /**
+ * Tells, if the given key is a required key.
+ * <p>
+ * Note that the SIG_KZ is a required key.
+ * </p>
+ * @param key The key to be tested if it is a required key.
+ * @return Returns true, if the key is required, false otherwise.
+ */
+ public static boolean isRequiredKey (String key)
+ {
+ if (key.equals(SIG_KZ))
+ {
+ return true;
+ }
+
+ for (int i = 0; i < REQUIRED_SIG_KEYS.length; i++)
+ {
+ if (key.equals(REQUIRED_SIG_KEYS[i]))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ public static String[] ALL_SIG_KEYS = new String[] { SIG_NAME, SIG_DATE,
+ SIG_ISSUER, SIG_VALUE, SIG_NORM, SIG_ID, SIG_LABEL, SIG_NUMBER, SIG_META };
+
+ public static byte [][] ALL_SIG_BREV = new byte[][] { { 'n', 'a', 'm' },
+ { 'd', 'a', 't' }, { 'i', 's', 's' }, { 'v', 'a', 'l' },
+ { 'n', 'o', 'r' }, { 's', 'i', 'd' }, { 'l', 'a', 'b' },
+ { 's', 'n', 'r' }, { 'm', 'e', 't' } };
+
+ // /**
+ // * Sorted representation of keys defined in rows
+ // */
+ // private ArrayList sortedSigKeys_ = new ArrayList();
+
+ // /**
+ // * Reference from signature key to there corresponding value
+ // */
+ // private Hashtable sigEntries_ = new Hashtable(8);
+
+ /**
+ * A list of all configured signature type definitions
+ */
+ private List signatureTypeDefinitions_ = new Vector();
+
+ /**
+ * A type-name to type-definition map
+ */
+ private Map typeDefMap_ = new HashMap();
+
+ // /**
+ // * A map of required keys used to reconstruct a signature block
+ // */
+ // private static HashMap requiredSigKeys_ = new HashMap();
+
+ /**
+ * A plain list of signature type names
+ */
+ ArrayList typeList_ = new ArrayList(4);
+
+ /**
+ * Used as singleton to read the singnature type definitions only one times of
+ * a session
+ */
+ private static SignatureTypes instance_ = null;
+
+ /**
+ * This is the private constructor method to provide a singleton instance of
+ * this class. It inits a normalizer, the settings reader, read the default
+ * styles and load the configured signature types.
+ *
+ * @throws SignatureTypesException
+ * @see SettingsReader
+ */
+ private SignatureTypes() throws SignatureTypesException
+ {
+ try
+ {
+ loadSettings();
+ }
+ catch (SettingsException e)
+ {
+ throw new SignatureTypesException(e);
+ }
+ setDefaultStyles();
+ loadSignatureTypes();
+ }
+
+ /**
+ * This static method returns the stored instance of this class. If the
+ * singleton does not exist, this method creates a new singleton and gives
+ * this instance back to the caller.
+ *
+ * @return the stored instance of this class
+ * @throws SignatureTypesException
+ */
+ public static SignatureTypes getInstance() throws SignatureTypesException
+ {
+ if (instance_ == null)
+ {
+ instance_ = new SignatureTypes();
+ }
+ return instance_;
+ }
+
+ /**
+ * This method load the signature definitions
+ *
+ * @throws SettingsException
+ *
+ * @throws SettingsException
+ * ErrorCode:101
+ */
+ private void loadSettings() throws SettingsException
+ {
+ if (settings_ == null)
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ // pTree_ = settings_.getPTree();
+ }
+
+ /**
+ * This method set the default styles for images, captions and values.
+ */
+ private void setDefaultStyles()
+ {
+ defaultImageStyle_.setPadding(3);
+ defaultImageStyle_.setHAlign(Style.CENTER);
+ defaultImageStyle_.setVAlign(Style.MIDDLE);
+ defaultImageStyle_.setBgColor(new Color(255, 255, 255));
+
+ defaultCaptionStyle_.setHAlign(Style.CENTER);
+ defaultCaptionStyle_.setVAlign(Style.MIDDLE);
+
+ defaultValueStyle_.setVAlign(Style.MIDDLE);
+ }
+
+ /**
+ * This method load the configured signature types. It stores the definition
+ * representations only if the type is set to ON. It stores the type
+ * definition object, the definition map and the simple type name list.
+ */
+ private void loadSignatureTypes()
+ {
+ if (settings_ != null)
+ {
+ ArrayList types = settings_.getKeys(TYPES);
+ for (int type_idx = 0; type_idx < types.size(); type_idx++)
+ {
+ String type = (String) types.get(type_idx);
+ if (STATE_ON.equals(settings_.getSetting(TYPES + "." + type, null)))
+ {
+ SignatureTypeDefinition sig_type_def;
+ try
+ {
+ sig_type_def = new SignatureTypeDefinition(settings_, type);
+ signatureTypeDefinitions_.add(sig_type_def);
+ typeDefMap_.put(type, sig_type_def);
+ typeList_.add(type);
+ }
+ catch (SignatureException e)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug(e.getMessage());
+ }
+ e.printStackTrace();
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * @return a arrayList (String) of signature types
+ */
+ public ArrayList getSignatureTypes()
+ {
+ return typeList_;
+ }
+
+ /**
+ * @return a list of signature type definitions
+ */
+ public List getSignatureTypeDefinitions()
+ {
+ return signatureTypeDefinitions_;
+ }
+
+ /**
+ * This method returns the corresponding signature type definition to a given
+ * type key
+ *
+ * @param type
+ * the key to get the signature type definition
+ * @return the stored signature type definition
+ */
+ public SignatureTypeDefinition getSignatureTypeDefinition(String type)
+ {
+ return (SignatureTypeDefinition) typeDefMap_.get(type);
+ }
+
+ public static String convertBrevToType (final byte [] brev)
+ {
+ for (int i = 0; i < ALL_SIG_BREV.length; i++)
+ {
+ if (ByteArrayUtils.compareByteArrays(ALL_SIG_BREV[i], 0, brev))
+ {
+ return ALL_SIG_KEYS[i];
+ }
+ }
+ return null;
+ }
+
+ public static byte [] convertTypeToBrev (final String type)
+ {
+ for (int i = 0; i < ALL_SIG_KEYS.length; i++)
+ {
+ if (ALL_SIG_KEYS.equals(type))
+ {
+ return ALL_SIG_BREV[i];
+ }
+ }
+ return null;
+ }
+
+ /**
+ * The standard toString method. Used for testing only.
+ *
+ * @return the string representation of the class
+ */
+ public String toString()
+ {
+ String strg = "";
+ for (int i = 0; i < signatureTypeDefinitions_.size(); i++)
+ {
+ SignatureTypeDefinition std = (SignatureTypeDefinition) signatureTypeDefinitions_.get(i);
+ strg += "----------TYPE:" + std.getType() + "----------\n";
+ strg += std.toString();
+ }
+ return strg;
+ }
+
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/X509Cert.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/X509Cert.java
new file mode 100644
index 0000000..64631cb
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/X509Cert.java
@@ -0,0 +1,462 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: X509Cert.java,v 1.4 2006/08/25 17:09:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.Serializable;
+import java.security.PublicKey;
+import java.security.cert.CertificateEncodingException;
+import java.security.cert.CertificateFactory;
+import java.security.cert.CertificateParsingException;
+import java.security.cert.X509Certificate;
+import java.util.List;
+
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.tools.CodingHelper;
+import at.knowcenter.wag.egov.egiz.tools.FileHelper;
+
+public class X509Cert implements Serializable
+{
+
+ /**
+ * SVUID.
+ */
+ private static final long serialVersionUID = 6945327015386694557L;
+
+ /**
+ * The x509 certificate binary string Base64 coded
+ */
+ private String certString_ = null;
+
+ /**
+ * The name value of the issuer
+ */
+ private String issuerName_ = null;
+
+ /**
+ * The serial number of the certificate
+ */
+ private String serialNumber_ = null;
+
+ /**
+ * The digest value of the certificate
+ */
+ private String certDigest_ = null;
+
+ /**
+ * The name value of the subject
+ */
+ private String subjectName_ = null;
+
+ /**
+ * The X509Certificate object
+ */
+ private X509Certificate x509Cert_ = null;
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(X509Cert.class);
+
+ /**
+ * The empty constructor not acessible from outside --> use the static init
+ * methods instead
+ */
+ private X509Cert()
+ {
+ }
+
+ /**
+ * Normalize the base64 coded .cer or .der string. Remove the begin and end
+ * statement and remove all whitespaces in the string. The result string
+ * (base64) is used by reconstructing the certiface sign by the verification
+ * process.
+ *
+ * @param certString
+ * the string to normalize
+ * @return the normalized cert string
+ */
+ private static String normalizeCertString(String certString)
+ {
+ certString = certString.replaceAll("-----BEGIN CERTIFICATE-----", "");
+ certString = certString.replaceAll("-----END CERTIFICATE-----", "");
+ certString = certString.replaceAll("\\s", "");
+ return certString;
+ }
+
+ /**
+ * This method initialzes a X509Certificate by a string value. It must be
+ * coded Base64 or as plain binary stream.
+ *
+ * @param certString
+ * the certificate string to analyse
+ * @return the X509Cert object
+ * @see CertificateFactory
+ * @see X509Certificate
+ */
+ public static X509Cert initByString(String certString)
+ {
+ if (certString == null)
+ {
+ return null;
+ }
+ certString = normalizeCertString(certString);
+ X509Cert x509_cert = new X509Cert();
+ x509_cert.setCertString(certString);
+ try
+ {
+ byte[] b64_dec = certString.getBytes("US-ASCII");
+ if (CodingHelper.isB64(b64_dec))
+ {
+ b64_dec = CodingHelper.decodeBase64(b64_dec);
+ }
+ else
+ {
+ b64_dec = CodingHelper.encodeBase64(b64_dec).getBytes("US-ASCII");
+ }
+ ByteArrayInputStream bais = new ByteArrayInputStream(b64_dec);
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
+ bais.close();
+ x509_cert.setX509Cert(cert);
+
+ String serial_num = cert.getSerialNumber().toString();
+ String issuer = cert.getIssuerDN().getName();
+ issuer = issuer.replaceAll(", ", ",");
+ String subject_name = cert.getSubjectDN().getName();
+ x509_cert.setSerialNumber(serial_num);
+ x509_cert.setIssuerName(issuer);
+ x509_cert.setSubjectName(subject_name);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Serial number from certificate:" + serial_num);
+ logger_.debug("Issuer name from certificate :" + issuer);
+ logger_.debug("Subject name from certificate :" + subject_name);
+ }
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ // nothing to do, cause certString is not X509 conformc
+ ce.printStackTrace();
+ }
+ catch (IOException ioe)
+ {
+ // nothing to do, cause certString is not X509 conform
+ ioe.printStackTrace();
+ }
+ return x509_cert;
+ }
+
+ public static X509Cert initByByteArray(byte[] data)
+ {
+ X509Cert x509_cert = new X509Cert();
+ try
+ {
+ ByteArrayInputStream bais = new ByteArrayInputStream(data);
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
+ bais.close();
+
+ x509_cert.setX509Cert(cert);
+
+ String serial_num = cert.getSerialNumber().toString();
+ String issuer = cert.getIssuerDN().getName();
+ issuer = issuer.replaceAll(", ", ",");
+ String subject_name = cert.getSubjectDN().getName();
+ x509_cert.setSerialNumber(serial_num);
+ x509_cert.setIssuerName(issuer);
+ x509_cert.setSubjectName(subject_name);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Serial number from certificate:" + serial_num);
+ logger_.debug("Issuer name from certificate :" + issuer);
+ logger_.debug("Subject name from certificate :" + subject_name);
+ }
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ // nothing to do, cause certString is not X509 conformc
+ ce.printStackTrace();
+ }
+ catch (IOException ioe)
+ {
+ // nothing to do, cause certString is not X509 conform
+ ioe.printStackTrace();
+ }
+
+ return x509_cert;
+ }
+
+ /**
+ * This method initialzes a X509Certificate by a file path value. The file
+ * must be a plain binary file like .cer format.
+ *
+ * @param filePath
+ * the certificate file to analyse
+ * @return the X509Cert object
+ * @see CertificateFactory
+ * @see X509Certificate
+ */
+ public static X509Cert initByFilePath(String filePath)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Add cert file:" + filePath);
+ }
+ if (filePath == null)
+ {
+ return null;
+ }
+ X509Cert x509_cert = new X509Cert();
+ try
+ {
+ FileInputStream fis = new FileInputStream(filePath);
+ X509Certificate cert = null;
+ try
+ {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ cert = (X509Certificate) cf.generateCertificate(fis);
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ fis.close();
+ String cert_string = FileHelper.readFromFile(filePath);
+ return initByString(cert_string);
+ }
+ fis.close();
+ x509_cert.setX509Cert(cert);
+ String cert_string = FileHelper.readFromFile(filePath);
+ x509_cert.setCertString(normalizeCertString(cert_string));
+
+ String serial_num = cert.getSerialNumber().toString();
+ String issuer = cert.getIssuerDN().getName();
+ issuer = issuer.replaceAll(", ", ",");
+ String subject_name = cert.getSubjectDN().getName();
+ x509_cert.setSerialNumber(serial_num);
+ x509_cert.setIssuerName(issuer);
+ x509_cert.setSubjectName(subject_name);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Serial number from certificate:" + serial_num);
+ logger_.debug("Issuer name from certificate :" + issuer);
+ logger_.debug("Subject name from certificate :" + subject_name);
+ }
+ }
+ catch (IOException ioe)
+ {
+ String cert_string = FileHelper.readFromFile(filePath);
+ return initByString(cert_string);
+ }
+ return x509_cert;
+
+ }
+
+ /**
+ * This method initialzes a X509Certificate by a file value. The file must be
+ * a plain binary file like .cer format.
+ *
+ * @param certFile
+ * the certificate file to analyse
+ * @return the X509Cert object
+ * @see CertificateFactory
+ * @see X509Certificate
+ */
+ public static X509Cert initByFile(File certFile)
+ {
+ return initByFilePath(certFile.getAbsolutePath());
+ }
+
+ /**
+ * This method checks if a certificate file is X509 conform.
+ *
+ * @return true if a certificate file is X509 conform, false otherwise
+ */
+ public boolean isX509Cert()
+ {
+ return x509Cert_ != null;
+ }
+
+ /**
+ * @return Returns the certificate digest value.
+ */
+ public String getCertDigest()
+ {
+ if (certDigest_ == null)
+ {
+ if (certString_ != null)
+ {
+ byte[] cert_b64 = CodingHelper.decodeBase64(certString_);
+ byte[] cert_hash = CodingHelper.buildDigest(cert_b64);
+ certDigest_ = new String(CodingHelper.encodeBase64(cert_hash));
+ }
+ }
+ return certDigest_;
+ }
+
+ /**
+ * @return Returns the certificate Base64 binary string.
+ */
+ public String getCertString()
+ {
+ return certString_;
+ }
+
+ /**
+ * @return Returns the issuer string.
+ */
+ public String getIssuerName()
+ {
+ return issuerName_;
+ }
+
+ /**
+ * @return Returns the serial number.
+ */
+ public String getSerialNumber()
+ {
+ return serialNumber_;
+ }
+
+ /**
+ * @return Returns the real X509Certifcate object.
+ * @see X509Certificate
+ */
+ public X509Certificate getX509Certificate()
+ {
+ return x509Cert_;
+ }
+
+ /**
+ * @return Returns the subject name.
+ */
+ public String getSubjectName()
+ {
+ return subjectName_;
+ }
+
+ // /**
+ // * @param certDigest
+ // * The certDigest to set.
+ // */
+ // private void setCertDigest(String certDigest)
+ // {
+ // certDigest_ = certDigest;
+ // }
+
+ /**
+ * @param certString
+ * The certString to set.
+ */
+ private void setCertString(String certString)
+ {
+ certString_ = certString;
+ }
+
+ /**
+ * @param issuerString
+ * The issuerString to set.
+ */
+ private void setIssuerName(String issuerString)
+ {
+ issuerName_ = issuerString;
+ }
+
+ /**
+ * @param serialNumber
+ * The serialNumber to set.
+ */
+ private void setSerialNumber(String serialNumber)
+ {
+ serialNumber_ = serialNumber;
+ }
+
+ /**
+ * @param cert
+ * The x509Cert to set.
+ */
+ private void setX509Cert(X509Certificate cert)
+ {
+ x509Cert_ = cert;
+ }
+
+ /**
+ * @param subjectName
+ * The subjectName to set.
+ */
+ private void setSubjectName(String subjectName)
+ {
+ subjectName_ = subjectName;
+ }
+
+ public byte[] getTBSCertificate() throws CertificateEncodingException
+ {
+ return x509Cert_.getTBSCertificate();
+ }
+
+ public String getSigAlgName()
+ {
+ return x509Cert_.getSigAlgName();
+ }
+
+ public String getSigAlgOID()
+ {
+ return x509Cert_.getSigAlgOID();
+ }
+
+ public List getExtendedKeyUsage()
+ {
+ List list = null;
+ try
+ {
+ list = x509Cert_.getExtendedKeyUsage();
+ if (list == null)
+ {
+ System.err.println("is realy null");
+ }
+ }
+ catch (CertificateParsingException e)
+ {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ /**
+ * @return the public key of the X509Certificate
+ */
+ public PublicKey getPublicKey()
+ {
+ return x509Cert_.getPublicKey();
+ }
+
+ /**
+ * This method checks, if a X509Certificate has a public key with the rsa
+ * algorithm.
+ *
+ * @return true if the public key is produced with rsa, false otherwise
+ */
+ public boolean isRSA()
+ {
+ return (x509Cert_.getPublicKey().getAlgorithm()).indexOf("RSA") >= 0;
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/A1Connector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/A1Connector.java
new file mode 100644
index 0000000..9144966
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/A1Connector.java
@@ -0,0 +1,55 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: A1Connector.java,v 1.2 2006/08/25 17:09:17 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig.connectors;
+
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.sig.ConnectorInformation;
+
+/**
+ * @author wprinz
+ */
+public class A1Connector extends BKUConnector
+{
+ /**
+ * ConnectorInformation that identifies this Connector to the system.
+ *
+ * @see at.knowcenter.wag.egov.egiz.sig.ConnectorFactory
+ * @see ConnectorInformation
+ */
+ public static final ConnectorInformation CONNECTOR_INFORMATION = new ConnectorInformation("a1", "A-1");
+
+ /**
+ * Constructor.
+ *
+ * @throws SignatureException
+ * F.e.
+ */
+ public A1Connector() throws SignatureException
+ {
+ super();
+ }
+
+ /**
+ * Overrides the type of the BKUConnector to use the A1 settings.
+ */
+ protected String getType()
+ {
+ return CONNECTOR_INFORMATION.getIdentifier();
+ }
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java
new file mode 100644
index 0000000..96fa81b
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUConnector.java
@@ -0,0 +1,813 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: BKUConnector.java,v 1.5 2006/10/31 08:18:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig.connectors;
+
+import java.io.UnsupportedEncodingException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+import at.knowcenter.wag.egov.egiz.sig.ConnectorInformation;
+import at.knowcenter.wag.egov.egiz.sig.LocalConnector;
+import at.knowcenter.wag.egov.egiz.sig.SignatureObject;
+import at.knowcenter.wag.egov.egiz.sig.SignatureResponse;
+import at.knowcenter.wag.egov.egiz.sig.X509Cert;
+import at.knowcenter.wag.egov.egiz.tools.CodingHelper;
+import at.knowcenter.wag.egov.egiz.tools.FileHelper;
+
+/**
+ * Connector for communicating with BKU.
+ *
+ * @author wlackner
+ * @author wprinz
+ */
+public class BKUConnector implements LocalConnector
+{
+ /**
+ * ConnectorInformation that identifies this Connector to the system.
+ *
+ * @see at.knowcenter.wag.egov.egiz.sig.ConnectorFactory
+ * @see ConnectorInformation
+ */
+ public static final ConnectorInformation CONNECTOR_INFORMATION = new ConnectorInformation("bku", "BKU");
+
+ /**
+ * The SettingsReader instance
+ */
+ private SettingsReader settings_ = null;
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(BKUConnector.class);
+
+ /**
+ * The empty constructor
+ */
+ public BKUConnector() throws SignatureException
+ {
+ loadSettings();
+ }
+
+ /**
+ * load the inital signature settings
+ *
+ * @see SettingsReader
+ */
+ private void loadSettings() throws SignatureException
+ {
+ if (settings_ == null)
+ {
+ try
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ catch (SettingsException e)
+ {
+ String log_message = "Can not load signature settings. Cause:\n" + e.getMessage();
+ logger_.error(log_message);
+ throw new SignatureException(101, log_message, e);
+ }
+ }
+ }
+
+ /**
+ * This method calls the BKU signing a given text. The signaton type is to
+ * used initializing the corresponding SigantureObject. The initialized
+ * SignatureObject is filled out by the parsed BKU-Response. <br>
+ * If an error request is send back from BKU, an error message is generated an
+ * an exception is thrown.
+ *
+ * @param sigType
+ * the type of the SignatureObject that should be returned
+ * @param userName
+ * the name of the user calling this method
+ * @param signText
+ * the text that shoulf be signed from BKU
+ * @return the complete SingatureObject of the given type filled by values
+ * from the BKU-Request
+ * @throws SignatureException
+ * @see SignatureObject
+ */
+ public SignatureObject doSign(String sigType, String userName, String signText) throws SignatureException
+ {
+ String request_string = prepareSignRequest(userName, signText, sigType);
+
+ String sign_url = getSignURL(sigType);
+ String response_string = sendRequest(sign_url, request_string);
+
+ return analyzeSignResponse(response_string, sigType);
+ }
+
+ /**
+ * This method generates the BKU verify prozess. It checks if the given
+ * SignatureObject is signed by MOA or BKU. The verify template string is
+ * filled out by the corresponding method.
+ *
+ * @param normalizedText
+ * the normalized text to verify
+ * @param sigObject
+ * the SignatureObject holding the singature values
+ * @return a SignatureResponse object if the verify prozess does not fails
+ * @throws SignatureException
+ * @see SignatureResponse
+ */
+ public SignatureResponse doVerify(String normalizedText,
+ SignatureObject sigObject) throws SignatureException
+ {
+ String request_string = prepareVerifyRequest(normalizedText, sigObject);
+
+ String verify_url = getVerifyURL(sigObject.getSignationType());
+ String response_string = sendRequest(verify_url, request_string);
+
+ return analyzeVerifyResponse(response_string);
+ }
+
+ /**
+ * This method parses the BKU-Response string. It separates the
+ * SignatureValue, X509IssuerName, SigningTime, X509SerialNumber,
+ * X509Certificate, CertDigest, DigestValue and the signation id-s. If the
+ * X509Certificate is extracted it would be stored in the certificates
+ * directory.
+ *
+ * @param xmlResponse
+ * the response string from the BKU sign-request
+ * @param sigObj
+ * the SignatureObject that should be filled
+ * @throws SignatureException
+ * ErrorCode (303, 304)
+ * @see SignatureObject
+ * @see CodingHelper
+ * @see X509Cert
+ */
+ private void parseCreateXMLResponse(String xmlResponse, SignatureObject sigObj) throws SignatureException
+ {
+ Pattern sig_val_p_s = Pattern.compile("<[\\w]*:?SignatureValue>");
+ Pattern sig_val_p_e = Pattern.compile("</[\\w]*:?SignatureValue>");
+ Pattern iss_nam_p_s = Pattern.compile("<[\\w]*:?X509IssuerName>");
+ Pattern iss_nam_p_e = Pattern.compile("</[\\w]*:?X509IssuerName>");
+ Pattern sig_tim_p_s = Pattern.compile("<[\\w]*:?SigningTime>");
+ Pattern sig_tim_p_e = Pattern.compile("</[\\w]*:?SigningTime>");
+ Pattern ser_num_p_s = Pattern.compile("<[\\w]*:?X509SerialNumber>");
+ Pattern ser_num_p_e = Pattern.compile("</[\\w]*:?X509SerialNumber>");
+ Pattern sig_cer_p_s = Pattern.compile("<[\\w]*:?X509Certificate>");
+ Pattern sig_cer_p_e = Pattern.compile("</[\\w]*:?X509Certificate>");
+
+ Pattern sig_cer_d_p_s = Pattern.compile("<[\\w]*:?CertDigest>");
+ Pattern sig_cer_d_p_e = Pattern.compile("</[\\w]*:?CertDigest>");
+ Pattern dig_val_p_s = Pattern.compile("<[\\w]*:?DigestValue>");
+ Pattern dig_val_p_e = Pattern.compile("</[\\w]*:?DigestValue>");
+
+ Matcher sig_val_m_s = sig_val_p_s.matcher(xmlResponse);
+ Matcher sig_val_m_e = sig_val_p_e.matcher(xmlResponse);
+ Matcher iss_nam_m_s = iss_nam_p_s.matcher(xmlResponse);
+ Matcher iss_nam_m_e = iss_nam_p_e.matcher(xmlResponse);
+ Matcher sig_tim_m_s = sig_tim_p_s.matcher(xmlResponse);
+ Matcher sig_tim_m_e = sig_tim_p_e.matcher(xmlResponse);
+ Matcher ser_num_m_s = ser_num_p_s.matcher(xmlResponse);
+ Matcher ser_num_m_e = ser_num_p_e.matcher(xmlResponse);
+ Matcher sig_cer_m_s = sig_cer_p_s.matcher(xmlResponse);
+ Matcher sig_cer_m_e = sig_cer_p_e.matcher(xmlResponse);
+
+ Matcher sig_cer_d_m_s = sig_cer_d_p_s.matcher(xmlResponse);
+ Matcher sig_cer_d_m_e = sig_cer_d_p_e.matcher(xmlResponse);
+
+ String sig_val = "";
+ String iss_nam = "";
+ String ser_num = "";
+ String sig_tim = "";
+ String sig_cer = "";
+ String sig_dig = "";
+
+ // SignatureValue
+ if (sig_val_m_s.find() && sig_val_m_e.find())
+ {
+ sig_val = xmlResponse.substring(sig_val_m_s.end(), sig_val_m_e.start());
+ sig_val = sig_val.replaceAll("\\s", "");
+ sigObj.setSignationValue(sig_val);
+ }
+ // X509IssuerName
+ if (iss_nam_m_s.find() && iss_nam_m_e.find())
+ {
+ iss_nam = xmlResponse.substring(iss_nam_m_s.end(), iss_nam_m_e.start());
+ sigObj.setSignationIssuer(iss_nam);
+ }
+ // X509SerialNumber
+ if (ser_num_m_s.find() && ser_num_m_e.find())
+ {
+ ser_num = xmlResponse.substring(ser_num_m_s.end(), ser_num_m_e.start());
+ sigObj.setSignationSerialNumber(ser_num);
+ }
+ // SigningTime
+ if (sig_tim_m_s.find() && sig_tim_m_e.find())
+ {
+ sig_tim = xmlResponse.substring(sig_tim_m_s.end(), sig_tim_m_e.start());
+ sigObj.setSignationDate(sig_tim);
+ }
+ // CertDigest
+ if (sig_cer_d_m_s.find() && sig_cer_d_m_e.find())
+ {
+ String cert_digest = xmlResponse.substring(sig_cer_d_m_s.end(), sig_cer_d_m_e.start());
+ Matcher dig_val_m_s = dig_val_p_s.matcher(cert_digest);
+ Matcher dig_val_m_e = dig_val_p_e.matcher(cert_digest);
+ if (dig_val_m_s.find() && dig_val_m_e.find())
+ {
+ sig_dig = cert_digest.substring(dig_val_m_s.end(), dig_val_m_e.start());
+ sigObj.setX509CertificateDigest(sig_dig);
+ }
+ }
+ // extract Subject Name from X509Certificate
+ if (sig_cer_m_s.find() && sig_cer_m_e.find())
+ {
+ sig_cer = xmlResponse.substring(sig_cer_m_s.end(), sig_cer_m_e.start());
+ sig_cer = sig_cer.replaceAll("\\s", "");
+ sigObj.setX509Certificate(sig_cer);
+ X509Cert cert = X509Cert.initByString(sig_cer);
+ if (cert.isX509Cert())
+ {
+ sigObj.setX509Certificate(cert.getCertString());
+ String serial_num = cert.getSerialNumber();
+ String subject_name = cert.getSubjectName();
+ if (!ser_num.equals(serial_num))
+ {
+ SignatureException se = new SignatureException(303, "Serialnumber of certificate and tag X509SerialNumber differs!");
+ throw se;
+ }
+ sigObj.setSignationName(subject_name);
+ }
+ }
+
+ // extract Signature Id's
+ String[] ids = new String[5];
+ ids[0] = extractId(xmlResponse, "signature-");
+ ids[1] = extractId(xmlResponse, "signed-data-reference-");
+ ids[2] = extractId(xmlResponse, "signed-data-object-");
+ ids[3] = extractId(xmlResponse, "etsi-data-reference-");
+ ids[4] = extractId(xmlResponse, "etsi-data-object-");
+ sigObj.setSignationIDs(ids);
+ }
+
+ /**
+ * This emthod extracts id-values from a text. The id is given by the name.
+ *
+ * @param text
+ * the id-value that should extract from
+ * @param name
+ * the id-key
+ * @return the value of the given key in the text
+ */
+ private String extractId(String text, String name)
+ {
+ String id = null;
+ int start_idx = text.indexOf(name) + name.length();
+ int end_idx = text.indexOf("\"", start_idx);
+ id = text.substring(start_idx, end_idx);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("extract id:" + name + id);
+ }
+ return id;
+ }
+
+ /**
+ * This method reads the verify template from the file system and fills out
+ * the template with the SignatureObject values.
+ *
+ * @param normalizedText
+ * the normalized text to veryfied
+ * @param sigObject
+ * the SignatureObject holding the singature values
+ * @return the filled verify template string
+ * @throws SignatureException
+ * ErrorCode (311, 312, 313)
+ * @see SignatureObject
+ * @see CodingHelper
+ */
+ public String getVerifyTemplate(String normalizedText,
+ SignatureObject sigObject) throws SignatureException
+ {
+ try
+ {
+ if (normalizedText == null || normalizedText.length() == 0)
+ {
+ SignatureException se = new SignatureException(311, "Document can not be verified because normalized text is empty.");
+ throw se;
+ }
+ if (sigObject == null)
+ {
+ SignatureException se = new SignatureException(312, "Document can not be verified because no signature object are set.");
+ throw se;
+ }
+
+ String verify_template = getVerifyTemplateFileName(sigObject.getSignationType());
+ String sig_prop_filename = getSigPropFileName(sigObject.getSignationType());
+
+ String ver_temp_str = FileHelper.readFromFile(SettingsReader.relocateFile(verify_template));
+ String sig_prop_str = FileHelper.readFromFile(SettingsReader.relocateFile(sig_prop_filename));
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_template);
+ logger_.debug(sig_prop_filename);
+ }
+
+ String x509_cert_string = sigObject.getX509CertificateString();
+ if (x509_cert_string == null)
+ {
+ SignatureException se = new SignatureException(313, "Document certificate is not defined.");
+ throw se;
+ }
+ String cert_alg = settings_.getValueFromKey("cert.alg.ecdsa");
+ X509Cert x509_cert = sigObject.getX509Cert();
+ if (x509_cert.isRSA())
+ {
+ cert_alg = settings_.getValueFromKey("cert.alg.rsa");
+ }
+
+ String[] ids = sigObject.getSignationIds();
+ sig_prop_str = sig_prop_str.replaceFirst("SigningTimeReplace", sigObject.getSignationDate());
+
+ String issuer_name = sigObject.getSignationIssuer();
+ // The issuer is already unicode, so it mustn't be encoded again.
+ //byte[] issuer_name = CodingHelper.encodeUTF8(sigObject.getSignationIssuer());
+ // new String(issuer_name); // this would double encode the String, not to mention the missing encoding
+ sig_prop_str = sig_prop_str.replaceFirst("X509IssuerNameReplace", issuer_name);
+
+ sig_prop_str = sig_prop_str.replaceFirst("X509SerialNumberReplace", sigObject.getSignationSerialNumber());
+ sig_prop_str = sig_prop_str.replaceFirst("DigestValueX509CertificateReplace", sigObject.getX509CertificateDigest());
+ sig_prop_str = sig_prop_str.replaceFirst("SigIdReplace", ids[0]);
+ sig_prop_str = sig_prop_str.replaceFirst("SigDataRefReplace", ids[1]);
+
+ ver_temp_str = ver_temp_str.replaceFirst("CertAlgReplace", cert_alg);
+ ver_temp_str = ver_temp_str.replaceFirst("TemplateQualifyingPropertiesReplace", sig_prop_str);
+ byte[] sig_prop_code = CodingHelper.buildDigest(sig_prop_str.getBytes("UTF-8"));
+ String sig_prop_hash = CodingHelper.encodeBase64(sig_prop_code);
+ ver_temp_str = ver_temp_str.replaceFirst("DigestValueSignedPropertiesReplace", sig_prop_hash);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("build digest from QualifyingProperties:start");
+ //logger_.debug("DATA :" + sig_prop_str);
+ logger_.debug("DIGEST:" + sig_prop_hash);
+ logger_.debug("build digest from QualifyingProperties:end");
+ }
+
+ ver_temp_str = ver_temp_str.replaceFirst("SignatureValueReplace", sigObject.getSignationValue());
+ ver_temp_str = ver_temp_str.replaceFirst("X509CertificateReplace", x509_cert_string);
+ byte[] data_value = normalizedText.getBytes("UTF-8");
+ byte[] data_value_hash = CodingHelper.buildDigest(data_value);
+ String object_data_hash = CodingHelper.encodeBase64(data_value_hash);
+ // String object_data = new String(data_value);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("build digest from data object:start");
+ //logger_.debug("DATA :" + normalizedText);
+ logger_.debug("DIGEST:" + object_data_hash);
+ logger_.debug("build digest from data object:end");
+ }
+
+ //String raw_b64 = CodingHelper.encodeUTF8AsBase64(normalizedText);
+ String raw_b64 = CodingHelper.encodeBase64(data_value);
+
+ ver_temp_str = ver_temp_str.replaceFirst("Base64ContentReplace", raw_b64);
+ ver_temp_str = ver_temp_str.replaceFirst("DigestValueSignedDataReplace", object_data_hash);
+
+ ver_temp_str = ver_temp_str.replaceAll("SigIdReplace", ids[0]);
+ ver_temp_str = ver_temp_str.replaceAll("SigDataRefReplace", ids[1]);
+ ver_temp_str = ver_temp_str.replaceAll("SigDataObjURIReplace", ids[2]);
+ ver_temp_str = ver_temp_str.replaceAll("EtsiDataRefReplace", ids[3]);
+ ver_temp_str = ver_temp_str.replaceAll("EtsiDataObjURIReplace", ids[4]);
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug("VERIFY REQUEST:" + ver_temp_str);
+ }
+
+ return ver_temp_str;
+ }
+ catch (UnsupportedEncodingException e)
+ {
+ throw new SignatureException(310, e);
+ }
+ }
+
+ /**
+ * This method parses the verify response string and return a
+ * SignatureResponse object. The SignatureResponse object is filled out by the
+ * response values from the BKU-response.
+ *
+ * @param xmlResponse
+ * the response values from the BKU-verify request
+ * @return SignatureResponse object
+ * @see SignatureResponse
+ */
+ private SignatureResponse parseVerifyXMLResponse(String xmlResponse)
+ {
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Try parsing the verify response");
+ }
+
+ Pattern sub_nam_p_s = Pattern.compile("<dsig:X509SubjectName>");
+ Pattern sub_nam_p_e = Pattern.compile("</dsig:X509SubjectName>");
+ Pattern iss_nam_p_s = Pattern.compile("<dsig:X509IssuerName>");
+ Pattern iss_nam_p_e = Pattern.compile("</dsig:X509IssuerName>");
+ Pattern ser_num_p_s = Pattern.compile("<dsig:X509SerialNumber>");
+ Pattern ser_num_p_e = Pattern.compile("</dsig:X509SerialNumber>");
+
+ Pattern sig_chk_p_s = Pattern.compile("<sl:SignatureCheck>");
+ Pattern sig_chk_p_e = Pattern.compile("</sl:SignatureCheck>");
+ Pattern man_chk_p_s = Pattern.compile("<sl:SignatureManifestCheck>");
+ Pattern man_chk_p_e = Pattern.compile("</sl:SignatureManifestCheck>");
+ Pattern cer_chk_p_s = Pattern.compile("<sl:CertificateCheck>");
+ Pattern cer_chk_p_e = Pattern.compile("</sl:CertificateCheck>");
+
+ Pattern code_p_s = Pattern.compile("<sl:Code>");
+ Pattern code_p_e = Pattern.compile("</sl:Code>");
+ Pattern info_p_s = Pattern.compile("<sl:Info>");
+ Pattern info_p_e = Pattern.compile("</sl:Info>");
+
+ Pattern cert_p_s = Pattern.compile("<dsig:X509Certificate>");
+ Pattern cert_p_e = Pattern.compile("</dsig:X509Certificate>");
+
+ Matcher sub_nam_m_s = sub_nam_p_s.matcher(xmlResponse);
+ Matcher sub_nam_m_e = sub_nam_p_e.matcher(xmlResponse);
+ Matcher iss_nam_m_s = iss_nam_p_s.matcher(xmlResponse);
+ Matcher iss_nam_m_e = iss_nam_p_e.matcher(xmlResponse);
+ Matcher ser_num_m_s = ser_num_p_s.matcher(xmlResponse);
+ Matcher ser_num_m_e = ser_num_p_e.matcher(xmlResponse);
+
+ Matcher sig_chk_m_s = sig_chk_p_s.matcher(xmlResponse);
+ Matcher sig_chk_m_e = sig_chk_p_e.matcher(xmlResponse);
+ Matcher man_chk_m_s = man_chk_p_s.matcher(xmlResponse);
+ Matcher man_chk_m_e = man_chk_p_e.matcher(xmlResponse);
+ Matcher cer_chk_m_s = cer_chk_p_s.matcher(xmlResponse);
+ Matcher cer_chk_m_e = cer_chk_p_e.matcher(xmlResponse);
+
+ Matcher cert_m_s = cert_p_s.matcher(xmlResponse);
+ Matcher cert_m_e = cert_p_e.matcher(xmlResponse);
+
+ SignatureResponse sig_res = new SignatureResponse();
+ if (sub_nam_m_s.find() && sub_nam_m_e.find())
+ {
+ String sub_nam = xmlResponse.substring(sub_nam_m_s.end(), sub_nam_m_e.start());
+ sig_res.setX509SubjectName(sub_nam);
+ }
+ if (iss_nam_m_s.find() && iss_nam_m_e.find())
+ {
+ String iss_nam = xmlResponse.substring(iss_nam_m_s.end(), iss_nam_m_e.start());
+ sig_res.setX509IssuerName(iss_nam);
+ }
+ if (ser_num_m_s.find() && ser_num_m_e.find())
+ {
+ String ser_num = xmlResponse.substring(ser_num_m_s.end(), ser_num_m_e.start());
+ sig_res.setX509SerialNumber(ser_num);
+ }
+ if (sig_chk_m_s.find() && sig_chk_m_e.find())
+ {
+ String sig_chk = xmlResponse.substring(sig_chk_m_s.end(), sig_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(sig_chk);
+ Matcher code_m_e = code_p_e.matcher(sig_chk);
+ Matcher info_m_s = info_p_s.matcher(sig_chk);
+ Matcher info_m_e = info_p_e.matcher(sig_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = sig_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setSignatureCheckCode(code);
+ }
+ if (info_m_s.find() && info_m_e.find())
+ {
+ String info = sig_chk.substring(info_m_s.end(), info_m_e.start());
+ sig_res.setSignatureCheckInfo(info);
+ }
+ }
+ if (man_chk_m_s.find() && man_chk_m_e.find())
+ {
+ String man_chk = xmlResponse.substring(man_chk_m_s.end(), man_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(man_chk);
+ Matcher code_m_e = code_p_e.matcher(man_chk);
+ Matcher info_m_s = info_p_s.matcher(man_chk);
+ Matcher info_m_e = info_p_e.matcher(man_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = man_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setSignatureManifestCheckCode(code);
+ }
+ if (info_m_s.find() && info_m_e.find())
+ {
+ String info = man_chk.substring(info_m_s.end(), info_m_e.start());
+ sig_res.setSignatureManifestCheckInfo(info);
+ }
+ }
+ if (cer_chk_m_s.find() && cer_chk_m_e.find())
+ {
+ String cer_chk = xmlResponse.substring(cer_chk_m_s.end(), cer_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(cer_chk);
+ Matcher code_m_e = code_p_e.matcher(cer_chk);
+ Matcher info_m_s = info_p_s.matcher(cer_chk);
+ Matcher info_m_e = info_p_e.matcher(cer_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = cer_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setCertificateCheckCode(code);
+ }
+ if (info_m_s.find() && info_m_e.find())
+ {
+ String info = cer_chk.substring(info_m_s.end(), info_m_e.start());
+ sig_res.setCertificateCheckInfo(info);
+ }
+ }
+ if (cert_m_s.find() && cert_m_e.find())
+ {
+ String cert_string = xmlResponse.substring(cert_m_s.end(), cert_m_e.start());
+
+ X509Cert resp_cert = X509Cert.initByString(cert_string);
+ sig_res.setCertificate(resp_cert);
+ }
+
+ return sig_res;
+ }
+
+ public String prepareSignRequest(String userName, String signText,
+ String signType) throws SignatureException
+ {
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Call " + getType() + " connector from user:" + userName);
+ }
+ String keybox_identifier = getSignKeyboxIdentifier(signType);
+ String sign_request_filename = getSignRequestTemplateFileName(signType);
+
+ String sign_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(sign_request_filename));
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(sign_request_filename + "_signText.xml :" + signText);
+ }
+ String raw_b64 = CodingHelper.encodeUTF8AsBase64(signText);
+ if (sign_req_str == null || raw_b64 == null)
+ {
+ throw new SignatureException(300, "Can not read the create xml request template");
+ }
+ sign_req_str = sign_req_str.replaceFirst("KeyboxIdentifierReplace", keybox_identifier);
+ sign_req_str = sign_req_str.replaceFirst("Base64ContentReplace", raw_b64);
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(sign_request_filename + "_request.xml :"+ sign_req_str);
+ }
+
+ return sign_req_str;
+ }
+
+ public String prepareVerifyRequest(String normalizedText,
+ SignatureObject sigObject) throws SignatureException
+ {
+ String verify_request = getVerifyRequestTemplateFileName(sigObject.getSignationType());
+ String verify_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(verify_request));
+
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_request);
+ }
+
+ String verify_template_str = null;
+ if (sigObject.isMOASigned())
+ {
+ MOAConnector moa_conn = new MOAConnector();
+ // get the MOA-template
+ verify_template_str = moa_conn.getVerifyTemplate(normalizedText, sigObject);
+ }
+ else
+ {
+ // get the BKU-template
+ verify_template_str = getVerifyTemplate(normalizedText, sigObject);
+ }
+ verify_req_str = verify_req_str.replaceFirst("XMLContentReplace", verify_template_str);
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_request + "_request.xml : " + verify_req_str);
+ }
+
+ return verify_req_str;
+ }
+
+ /**
+ * Sends the request to the given URL.
+ *
+ * @param url
+ * The URL.
+ * @param request_string
+ * The request string.
+ * @return Returns the response string.
+ * @throws SignatureException
+ * F.e.
+ */
+ protected String sendRequest(String url, String request_string) throws SignatureException
+ {
+ try
+ {
+ String response_string = BKUPostConnection.doPostRequest(url, request_string);
+ return response_string;
+ }
+ catch (Exception e)
+ {
+ SignatureException se = new SignatureException(320, e);
+ throw se;
+ }
+ }
+
+ public SignatureObject analyzeSignResponse(String response_string,
+ String sigType) throws SignatureException
+ {
+ //String sign_request_filename = getSignRequestTemplateFileName(sigType);
+
+ SignatureObject sig_obj = new SignatureObject();
+ sig_obj.setRawSignatureResponse(response_string);
+ try
+ {
+ sig_obj.setSigType(sigType);
+ sig_obj.initByType();
+ }
+ catch (SignatureTypesException e)
+ {
+ SignatureException se = new SignatureException(300, "Cannot init signature object with type:" + sigType, e);
+ throw se;
+ }
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Signature Type is:" + sig_obj.getSignationType());
+ }
+
+ if (!response_string.equals(""))
+ {
+ Pattern erc_p_s = Pattern.compile("<[\\w]*:?ErrorCode>");
+ Pattern erc_p_e = Pattern.compile("</[\\w]*:?ErrorCode>");
+ Matcher erc_m_s = erc_p_s.matcher(response_string);
+ Matcher erc_m_e = erc_p_e.matcher(response_string);
+ // System.err.println(response_string);
+
+ if (erc_m_s.find() && erc_m_e.find())
+ {
+ if (logger_.isEnabledFor(Level.ERROR))
+ {
+ //logger_.debug(sign_request_filename + "_response.xml : " + response_string);
+ logger_.error("BKU Error response: " + response_string);
+ }
+ Pattern erm_p_s = Pattern.compile("<[\\w]*:?Info>");
+ Pattern erm_p_e = Pattern.compile("</[\\w]*:?Info>");
+ Matcher erm_m_s = erm_p_s.matcher(response_string);
+ Matcher erm_m_e = erm_p_e.matcher(response_string);
+ SignatureException se = new SignatureException(0, "BKUSigExc");
+ String error_code = response_string.substring(erc_m_s.end(), erc_m_e.start());
+ se.setExternalErrorCode(error_code);
+ if (erm_m_s.find() && erm_m_e.find())
+ {
+ String error_mess = response_string.substring(erm_m_s.end(), erm_m_e.start());
+ se.setExternalErrorMessage(error_mess);
+ }
+ throw se;
+ }
+ else
+ {
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(sign_request_filename + "_response.xml : " + response_string);
+ }
+ parseCreateXMLResponse(response_string, sig_obj);
+ }
+ }
+ sig_obj.setSigResponse(response_string);
+ return sig_obj;
+ }
+
+ public SignatureResponse analyzeVerifyResponse(String response_string) throws SignatureException
+ {
+ if (!response_string.equals(""))
+ {
+ Pattern erc_p_s = Pattern.compile("<[\\w]*:?ErrorCode>");
+ Pattern erc_p_e = Pattern.compile("</[\\w]*:?ErrorCode>");
+ Matcher erc_m_s = erc_p_s.matcher(response_string);
+ Matcher erc_m_e = erc_p_e.matcher(response_string);
+
+ if (erc_m_s.find() && erc_m_e.find())
+ {
+ if (logger_.isEnabledFor(Level.ERROR))
+ {
+ //logger_.debug(getType() + "_response.xml : " + response_string);
+ logger_.error(getType() + "_response.xml : " + response_string);
+ }
+ Pattern erm_p_s = Pattern.compile("<[\\w]*:?Info>");
+ Pattern erm_p_e = Pattern.compile("</[\\w]*:?Info>");
+ Matcher erm_m_s = erm_p_s.matcher(response_string);
+ Matcher erm_m_e = erm_p_e.matcher(response_string);
+ SignatureException se = new SignatureException(0, "BKUSigExc");
+ if (erc_m_s.find() && erc_m_e.find())
+ {
+ String error_code = response_string.substring(erc_m_s.end(), erc_m_e.start());
+ se.setExternalErrorCode(error_code);
+ }
+ if (erm_m_s.find() && erm_m_e.find())
+ {
+ String error_mess = response_string.substring(erm_m_s.end(), erm_m_e.start());
+ se.setExternalErrorMessage(error_mess);
+ }
+ throw se;
+ }
+ else
+ {
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(getType() + "_response.xml : " + response_string);
+ }
+ return parseVerifyXMLResponse(response_string);
+ }
+ }
+ return null;
+ }
+
+ protected String getConnectorValueFromProfile(String profile, String key)
+ {
+ String value = settings_.getValueFromKey("sig_obj." + profile + "." + key);
+ if (value == null)
+ {
+ value = settings_.getValueFromKey(key);
+ }
+ return value;
+ }
+
+ public String getSignURL(String profile)
+ {
+ final String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".url";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSignRequestTemplateFileName(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".request";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSignKeyboxIdentifier(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".KeyboxIdentifier";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ public String getVerifyURL(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".url";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getVerifyRequestTemplateFileName(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".request";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getVerifyTemplateFileName(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".template";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSigPropFileName(String profile)
+ {
+ String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".template.SP";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ /**
+ * Returns the type of this BKU-like connector.
+ *
+ * <p>
+ * All settings keys will be prefixed by this type. So to reuse the BKU
+ * connector, a deriving class has to implement this method specifying an own
+ * type.
+ * </p>
+ *
+ * @return Returns the type of this BKU-like connector.
+ */
+ protected String getType()
+ {
+ return CONNECTOR_INFORMATION.getIdentifier();
+ }
+} \ No newline at end of file
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUPostConnection.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUPostConnection.java
new file mode 100644
index 0000000..773b248
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/BKUPostConnection.java
@@ -0,0 +1,95 @@
+/**
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: BKUPostConnection.java,v 1.3 2006/10/11 07:56:10 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig.connectors;
+
+import java.io.IOException;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.NameValuePair;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.commons.httpclient.params.HttpMethodParams;
+import org.apache.log4j.Logger;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+
+/**
+ * @author wprinz
+ */
+public abstract class BKUPostConnection
+{
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(BKUPostConnection.class);
+
+ /**
+ * This method connects the BKU server getting the request and the url. The
+ * request is an XML Message send and recieve by the HttpClient module. The
+ * Response message of the BKU server is is send back to the calling method.
+ *
+ * @param url
+ * the URL which the BKU server is running
+ * @param request
+ * the request string (XML) to send.
+ * @return the response string (XML) of the BKU server
+ * @throws IOException
+ * @throws HttpException
+ * ErrorCode:320
+ */
+ public static String doPostRequest(String url, String request) throws HttpException, IOException
+ {
+
+ PostMethod post_method = new PostMethod(url);
+
+ // It is very important to specify the charset of the content (the request)
+ // as UTF-8 this way.
+ // The HttpClient will then perform the URL encoding assuming that the
+ // request is UTF-8 as the BKU expects.
+ // If the MethodParams are omitted, the HttpClient will assume that the
+ // request is ISO-8859-1 and thereby the BKU cannot properly decode it.
+ HttpMethodParams method_params = new HttpMethodParams();
+ method_params.setContentCharset("UTF-8");
+ post_method.setParams(method_params);
+
+ // This is just a hint: do not set the content-type this way or the BKU will
+ // assume it as text/XML, but the HttpClient sends it as URL-encoded.
+ // The HttpClient will automatically generate the proper Content-Type:
+ // application/x-www-form-urlencoded
+ // post.addRequestHeader(new Header("Content-Type",
+ // "text/xml;charset=UTF-8"));
+
+ NameValuePair[] data = { new NameValuePair("XMLRequest", request) };
+ post_method.setRequestBody(data);
+
+ HttpClient http_client = new HttpClient();
+ int method_response = http_client.executeMethod(post_method);
+ logger_.debug("method_response = " + method_response);
+
+ byte[] response_body = post_method.getResponseBody();
+ String response_string = new String(response_body, "UTF-8");
+
+ // Alternatively this could be used.
+ // The HttpClient is assumed to use the Content-Type provided by the
+ // response.
+ // String response_string = post.getResponseBodyAsString();
+
+ return response_string;
+ }
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/ConnectorConfigurationKeys.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/ConnectorConfigurationKeys.java
new file mode 100644
index 0000000..a50dd1e
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/ConnectorConfigurationKeys.java
@@ -0,0 +1,35 @@
+/**
+ *
+ */
+package at.knowcenter.wag.egov.egiz.sig.connectors;
+
+/**
+ * This class contains the key constants used by the Connectors to retrieve
+ * templates etc. from the Configuration.
+ *
+ * @author wprinz
+ */
+public abstract class ConnectorConfigurationKeys
+{
+
+ /**
+ * The application mode sign
+ */
+ public static final String VALUE_MODE_SIGN = "sign";
+
+ /**
+ * The application mode verify
+ */
+ public static final String VALUE_MODE_VERIFY = "verify";
+
+ /**
+ * The key used to read out the available for web property.
+ */
+ public static final String AVAILABLE_FOR_WEB = "available_for_web";
+
+ /**
+ * The key used to read out the available for commandline property.
+ */
+ public static final String AVAILABLE_FOR_COMMANDLINE = "available_for_commandline";
+
+}
diff --git a/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/MOAConnector.java b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/MOAConnector.java
new file mode 100644
index 0000000..de1ee57
--- /dev/null
+++ b/src/main/java/at/knowcenter/wag/egov/egiz/sig/connectors/MOAConnector.java
@@ -0,0 +1,880 @@
+/*
+ * <copyright> Copyright (c) 2006 by Know-Center, Graz, Austria </copyright>
+ *
+ * This software is the confidential and proprietary information of Know-Center,
+ * Graz, Austria. You shall not disclose such Confidential Information and shall
+ * use it only in accordance with the terms of the license agreement you entered
+ * into with Know-Center.
+ *
+ * KNOW-CENTER MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR
+ * NON-INFRINGEMENT. KNOW-CENTER SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
+ * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
+ * DERIVATIVES.
+ *
+ * $Id: MOAConnector.java,v 1.5 2006/10/31 08:18:41 wprinz Exp $
+ */
+package at.knowcenter.wag.egov.egiz.sig.connectors;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.UnsupportedEncodingException;
+import java.util.Vector;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.xml.namespace.QName;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.rpc.Call;
+import javax.xml.rpc.Service;
+import javax.xml.rpc.ServiceFactory;
+
+import org.apache.axis.message.SOAPBodyElement;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.xml.serialize.OutputFormat;
+import org.apache.xml.serialize.XMLSerializer;
+import org.w3c.dom.Document;
+
+import at.knowcenter.wag.egov.egiz.cfg.ConfigLogger;
+import at.knowcenter.wag.egov.egiz.cfg.SettingsReader;
+import at.knowcenter.wag.egov.egiz.exceptions.SettingsException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureException;
+import at.knowcenter.wag.egov.egiz.exceptions.SignatureTypesException;
+import at.knowcenter.wag.egov.egiz.exceptions.WebException;
+import at.knowcenter.wag.egov.egiz.sig.Connector;
+import at.knowcenter.wag.egov.egiz.sig.ConnectorInformation;
+import at.knowcenter.wag.egov.egiz.sig.SignatureObject;
+import at.knowcenter.wag.egov.egiz.sig.SignatureResponse;
+import at.knowcenter.wag.egov.egiz.sig.X509Cert;
+import at.knowcenter.wag.egov.egiz.tools.CodingHelper;
+import at.knowcenter.wag.egov.egiz.tools.FileHelper;
+
+/**
+ * Connector to access the MOA service.
+ *
+ * @author wlackner
+ * @author wprinz
+ */
+public class MOAConnector implements Connector
+{
+ /**
+ * ConnectorInformation that identifies this Connector to the system.
+ *
+ * @see at.knowcenter.wag.egov.egiz.sig.ConnectorFactory
+ * @see ConnectorInformation
+ */
+ public static final ConnectorInformation CONNECTOR_INFORMATION = new ConnectorInformation("moa", "MOA");
+
+ /**
+ * The class type value.
+ *
+ * <p>
+ * Just for convenience.
+ * </p>
+ */
+ private static final String TYPE = CONNECTOR_INFORMATION.getIdentifier();
+
+ /**
+ * The connector description.
+ */
+ public static final String DESCRIPTION = "MOA";
+
+ /**
+ * The SettingsReader instance
+ */
+ private SettingsReader settings_ = null;
+
+ /**
+ * MOA siganture verification mode
+ */
+ public static final String SERVICE_VERIFY = "SignatureVerification";
+
+ /**
+ * MOA siganture creation mode
+ */
+ public static final String SERVICE_SIGN = "SignatureCreation";
+
+ /**
+ * The logger definition.
+ */
+ private static final Logger logger_ = ConfigLogger.getLogger(MOAConnector.class);
+
+ /**
+ * The empty constructor
+ */
+ public MOAConnector() throws SignatureException
+ {
+ loadSettings();
+ }
+
+ /**
+ * load the inital signature settings
+ *
+ * @see SettingsReader
+ */
+ private void loadSettings() throws SignatureException
+ {
+ if (settings_ == null)
+ {
+ try
+ {
+ settings_ = SettingsReader.getInstance();
+ }
+ catch (SettingsException e)
+ {
+ String log_message = "Can not load signature settings. Cause:\n" + e.getMessage();
+ logger_.error(log_message);
+ throw new SignatureException(101, log_message, e);
+ }
+ }
+ }
+
+ /**
+ * This method calls the MOA signing a given text. The signaton type is to
+ * used initializing the corresponding SigantureObject. The initialized
+ * SignatureObject is filled out by the parsed MOA-Response. <br>
+ * If an error request is send back from MOA, an error message is generated an
+ * an exception is thrown.
+ *
+ * @param sigType
+ * the type of the SignatureObject that should be returned
+ * @param userName
+ * the name of the user calling this method
+ * @param signText
+ * the text that shoulf be signed from MOA
+ * @return the complete SingatureObject of the given type filled by values
+ * from the MOA-Request
+ * @throws SignatureException
+ * ErrorCode 300
+ * @see SignatureObject
+ */
+ public SignatureObject doSign(String sigType, String userName, String signText) throws SignatureException
+ {
+ SignatureObject sig_obj = new SignatureObject();
+ try
+ {
+ sig_obj.setSigType(sigType);
+ sig_obj.initByType();
+ }
+ catch (SignatureTypesException e)
+ {
+ SignatureException se = new SignatureException(300, "Can ot init signature object with type:" + sigType, e);
+ throw se;
+ }
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("Signature Type is:" + sig_obj.getSignationType());
+ }
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Call " + TYPE + " from user:" + userName);
+ }
+
+ String url = getSignURL(sigType);
+
+ String sign_request_filename = getSignRequestTemplateFileName(sigType);
+ String key_ident = getSignKeyIdentifier(sigType);
+ String sign_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(sign_request_filename));
+ if (sign_req_str == null)
+ {
+ SignatureException se = new SignatureException(300, "File not found:" + sign_request_filename);
+ throw se;
+ }
+
+ sign_req_str = sign_req_str.replaceFirst("KeyIdentifierReplace", key_ident);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("error_signature_response = " + sign_req_str);
+ // FileHelper.writeToFile(sign_request_filename + "_signText.xml",
+ // signText);
+ }
+ // sign_req_str = sign_req_str.replaceFirst("XMLContentReplace", signText);
+ // now use the the base64 Template
+ signText = CodingHelper.encodeUTF8AsBase64(signText);
+ sign_req_str = sign_req_str.replaceFirst("Base64ContentReplace", signText);
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(sign_req_str);
+ // FileHelper.writeToFile(sign_request_filename + "_request.xml",
+ // sign_req_str);
+ }
+
+ String response_string = "";
+ try
+ {
+ response_string = MOAConnector.connectMOA(sign_req_str, MOAConnector.SERVICE_SIGN, url);
+ sig_obj.setRawSignatureResponse(response_string);
+ }
+ catch (WebException we)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ we.printStackTrace();
+ }
+ SignatureException se = new SignatureException(we.getErrorCode(), we);
+ throw se;
+ }
+
+ if (!response_string.equals(""))
+ {
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("get MOA response");
+ }
+ Pattern erc_p_s = Pattern.compile("<ErrorCode>");
+ Pattern erc_p_e = Pattern.compile("</ErrorCode>");
+ Matcher erc_m_s = erc_p_s.matcher(response_string);
+ Matcher erc_m_e = erc_p_e.matcher(response_string);
+ // System.err.println(response_string);
+
+ if (erc_m_s.find() && erc_m_e.find())
+ {
+ if (logger_.isEnabledFor(Level.ERROR))
+ {
+ logger_.error("error_signature_response = " + response_string);
+ // FileHelper.writeToFile(sign_request_filename + "_response.xml",
+ // response_string);
+ //logger_.error("Write error response to file:" + sign_request_filename + "_response.xml");
+ }
+ Pattern erm_p_s = Pattern.compile("<Info>");
+ Pattern erm_p_e = Pattern.compile("</Info>");
+ Matcher erm_m_s = erm_p_s.matcher(response_string);
+ Matcher erm_m_e = erm_p_e.matcher(response_string);
+
+ String error_code = response_string.substring(erc_m_s.end(), erc_m_e.start());
+ logger_.debug("error_code = " + error_code);
+ String error_mess = "";
+ if (erm_m_s.find() && erm_m_e.find())
+ {
+ error_mess = response_string.substring(erm_m_s.end(), erm_m_e.start());
+ logger_.debug(error_mess);
+ }
+ SignatureException se = new SignatureException(0, "MOASigExc ext error code = " + error_code + ", err_mess = " + error_mess);
+ se.setExternalErrorCode(error_code);
+ se.setExternalErrorMessage(error_mess);
+ throw se;
+ }
+ else
+ {
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("error_signature_response = " + response_string);
+ // FileHelper.writeToFile(sign_request_filename + "_response.xml",
+ // response_string);
+ }
+ parseCreateXMLResponse(response_string, sig_obj);
+ }
+ }
+ sig_obj.setSigResponse(response_string);
+ return sig_obj;
+ }
+
+ /**
+ * This method parses the MOA-Response string. It separates the
+ * SignatureValue, X509IssuerName, SigningTime, X509SerialNumber,
+ * X509Certificate, CertDigest and DigestValues. If the X509Certificate is
+ * extracted it would be stored in the certificates directory.
+ *
+ * @param xmlResponse
+ * the response string from the MOA sign-request
+ * @param sigObj
+ * the SignatureObject that should be filled
+ * @throws SignatureException
+ * ErrorCode (303, 304)
+ * @see SignatureObject
+ * @see CodingHelper
+ * @see X509Cert
+ */
+ private void parseCreateXMLResponse(String xmlResponse, SignatureObject sigObj) throws SignatureException
+ {
+ Pattern sig_val_p_s = Pattern.compile("<[\\w]*:?SignatureValue>");
+ Pattern sig_val_p_e = Pattern.compile("</[\\w]*:?SignatureValue>");
+ Pattern iss_nam_p_s = Pattern.compile("<[\\w]*:?X509IssuerName>");
+ Pattern iss_nam_p_e = Pattern.compile("</[\\w]*:?X509IssuerName>");
+ Pattern sig_tim_p_s = Pattern.compile("<[\\w]*:?SigningTime>");
+ Pattern sig_tim_p_e = Pattern.compile("</[\\w]*:?SigningTime>");
+ Pattern ser_num_p_s = Pattern.compile("<[\\w]*:?X509SerialNumber>");
+ Pattern ser_num_p_e = Pattern.compile("</[\\w]*:?X509SerialNumber>");
+ Pattern sig_cer_p_s = Pattern.compile("<[\\w]*:?X509Certificate>");
+ Pattern sig_cer_p_e = Pattern.compile("</[\\w]*:?X509Certificate>");
+
+ Pattern sig_cer_d_p_s = Pattern.compile("<[\\w]*:?CertDigest>");
+ Pattern sig_cer_d_p_e = Pattern.compile("</[\\w]*:?CertDigest>");
+ Pattern dig_val_p_s = Pattern.compile("<[\\w]*:?DigestValue>");
+ Pattern dig_val_p_e = Pattern.compile("</[\\w]*:?DigestValue>");
+
+ Matcher sig_val_m_s = sig_val_p_s.matcher(xmlResponse);
+ Matcher sig_val_m_e = sig_val_p_e.matcher(xmlResponse);
+ Matcher iss_nam_m_s = iss_nam_p_s.matcher(xmlResponse);
+ Matcher iss_nam_m_e = iss_nam_p_e.matcher(xmlResponse);
+ Matcher sig_tim_m_s = sig_tim_p_s.matcher(xmlResponse);
+ Matcher sig_tim_m_e = sig_tim_p_e.matcher(xmlResponse);
+ Matcher ser_num_m_s = ser_num_p_s.matcher(xmlResponse);
+ Matcher ser_num_m_e = ser_num_p_e.matcher(xmlResponse);
+ Matcher sig_cer_m_s = sig_cer_p_s.matcher(xmlResponse);
+ Matcher sig_cer_m_e = sig_cer_p_e.matcher(xmlResponse);
+
+ Matcher sig_cer_d_m_s = sig_cer_d_p_s.matcher(xmlResponse);
+ Matcher sig_cer_d_m_e = sig_cer_d_p_e.matcher(xmlResponse);
+
+ String sig_val = "";
+ String iss_nam = "";
+ String ser_num = "";
+ String sig_tim = "";
+ String sig_cer = "";
+ String sig_dig = "";
+
+ // SignatureValue
+ if (sig_val_m_s.find() && sig_val_m_e.find())
+ {
+ sig_val = xmlResponse.substring(sig_val_m_s.end(), sig_val_m_e.start());
+ sig_val = sig_val.replaceAll("\\s", "");
+ sigObj.setSignationValue(sig_val);
+ }
+ // X509IssuerName
+ if (iss_nam_m_s.find() && iss_nam_m_e.find())
+ {
+ iss_nam = xmlResponse.substring(iss_nam_m_s.end(), iss_nam_m_e.start());
+ sigObj.setSignationIssuer(iss_nam);
+ }
+ // X509SerialNumber
+ if (ser_num_m_s.find() && ser_num_m_e.find())
+ {
+ ser_num = xmlResponse.substring(ser_num_m_s.end(), ser_num_m_e.start());
+ sigObj.setSignationSerialNumber(ser_num);
+ }
+ // SigningTime
+ if (sig_tim_m_s.find() && sig_tim_m_e.find())
+ {
+ sig_tim = xmlResponse.substring(sig_tim_m_s.end(), sig_tim_m_e.start());
+ sigObj.setSignationDate(sig_tim);
+ }
+ // CertDigest
+ if (sig_cer_d_m_s.find() && sig_cer_d_m_e.find())
+ {
+ String cert_digest = xmlResponse.substring(sig_cer_d_m_s.end(), sig_cer_d_m_e.start());
+ Matcher dig_val_m_s = dig_val_p_s.matcher(cert_digest);
+ Matcher dig_val_m_e = dig_val_p_e.matcher(cert_digest);
+ if (dig_val_m_s.find() && dig_val_m_e.find())
+ {
+ sig_dig = cert_digest.substring(dig_val_m_s.end(), dig_val_m_e.start());
+ sigObj.setX509CertificateDigest(sig_dig);
+ }
+ }
+ // extract Subject Name from X509Certificate
+ if (sig_cer_m_s.find() && sig_cer_m_e.find())
+ {
+ sig_cer = xmlResponse.substring(sig_cer_m_s.end(), sig_cer_m_e.start());
+ sig_cer = sig_cer.replaceAll("\\s", "");
+ X509Cert cert = X509Cert.initByString(sig_cer);
+ if (cert.isX509Cert())
+ {
+ sigObj.setX509Certificate(cert.getCertString());
+ String serial_num = cert.getSerialNumber();
+ String subject_name = cert.getSubjectName();
+ if (!ser_num.equals(serial_num))
+ {
+ SignatureException se = new SignatureException(303, "Serialnumber of certificate and tag X509SerialNumber differs!");
+ throw se;
+ }
+ sigObj.setSignationName(subject_name);
+ }
+ }
+ }
+
+ /**
+ * This method reads the verify template from the file system and fills out
+ * the template with the SignatureObject values.
+ *
+ * @param normalizedText
+ * the normalized text to veryfied
+ * @param sigObject
+ * the SignatureObject holding the singature values
+ * @return the filled verify template string
+ * @throws SignatureException
+ * ErrorCode (311, 312, 313)
+ * @see SignatureObject
+ * @see CodingHelper
+ */
+ public String getVerifyTemplate(String normalizedText,
+ SignatureObject sigObject) throws SignatureException
+ {
+ try
+ {
+ if (normalizedText == null || normalizedText.length() == 0)
+ {
+ SignatureException se = new SignatureException(311, "Document can not be verified because normalized text is empty.");
+ throw se;
+ }
+ if (sigObject == null)
+ {
+ SignatureException se = new SignatureException(312, "Document can not be verified because no signature object are set.");
+ throw se;
+ }
+ String verify_template = getVerifyTemplateFileName(sigObject.getSignationType());
+ String sig_prop_template = getSigPropFileName(sigObject.getSignationType());
+ String verify_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(verify_template));
+ String sig_prop_str = FileHelper.readFromFile(SettingsReader.relocateFile(sig_prop_template));
+
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_template);
+ //logger_.debug(sig_prop_template);
+ }
+
+ String x509Certificate = sigObject.getX509CertificateString();
+ if (x509Certificate == null)
+ {
+ SignatureException se = new SignatureException(313, "Document certificate is not defined.");
+ throw se;
+ }
+ String cert_alg = settings_.getValueFromKey("cert.alg.ecdsa");
+ X509Cert x509_cert = sigObject.getX509Cert();
+ if (x509_cert.isRSA())
+ {
+ cert_alg = settings_.getValueFromKey("cert.alg.rsa");
+ }
+
+ sig_prop_str = sig_prop_str.replaceFirst("SigningTimeReplace", sigObject.getSignationDate());
+ // The issuer is already a valid Unicode String.
+ // No need to convert it - not to mention the missing encoding.
+ // byte[] issuer_name =
+ // CodingHelper.encodeUTF8(sigObject.getSignationIssuer());
+ // new String(issuer_name)
+ sig_prop_str = sig_prop_str.replaceFirst("X509IssuerNameReplace", sigObject.getSignationIssuer());
+ sig_prop_str = sig_prop_str.replaceFirst("X509SerialNumberReplace", sigObject.getSignationSerialNumber());
+ sig_prop_str = sig_prop_str.replaceFirst("DigestValueX509CertificateReplace", sigObject.getX509CertificateDigest());
+
+ verify_req_str = verify_req_str.replaceFirst("CertAlgReplace", cert_alg);
+ verify_req_str = verify_req_str.replaceFirst("TemplateSignedPropertiesReplace", sig_prop_str);
+ byte[] sig_prop_code = CodingHelper.buildDigest(sig_prop_str.getBytes("UTF-8")); // added
+ // the
+ // ("UTF-8")
+ // encoding
+ String sig_prop_hash = CodingHelper.encodeBase64(sig_prop_code);
+ verify_req_str = verify_req_str.replaceFirst("DigestValueSignedPropertiesReplace", sig_prop_hash);
+ if (logger_.isDebugEnabled())
+ {
+ logger_.debug("build digest from SignedProperties:start");
+ //logger_.debug("DATA :" + sig_prop_str);
+ logger_.debug("DIGEST:" + sig_prop_hash);
+ logger_.debug("build digest from SignedProperties:end");
+ }
+
+ verify_req_str = verify_req_str.replaceFirst("SignatureValueReplace", sigObject.getSignationValue());
+ verify_req_str = verify_req_str.replaceFirst("X509CertificateReplace", x509Certificate);
+ byte[] data_value = normalizedText.getBytes("UTF-8");
+ byte[] data_value_hash = CodingHelper.buildDigest(data_value);
+ // byte[] data_value_hash =
+ // CodingHelper.buildDigest(normalizedText.getBytes());
+ String object_data_hash = CodingHelper.encodeBase64(data_value_hash);
+ //String object_data = normalizedText; // new String(data_value);
+ // System.err.println(object_data_hash);
+ // very_req_str = very_req_str.replaceFirst("ObjectDataReplace",
+ // object_data);
+ String raw_b64 = CodingHelper.encodeBase64(data_value);
+ verify_req_str = verify_req_str.replaceFirst("Base64ContentReplace", raw_b64);
+
+ verify_req_str = verify_req_str.replaceFirst("DigestValueSignedDataReplace", object_data_hash);
+ if (logger_.isDebugEnabled())
+ {
+ // FileHelper.writeToFile(verify_template + "_verifyText.xml",
+ // normalizedText);
+ logger_.debug("build digest from data object:start");
+ //logger_.debug("DATA :" + object_data);
+ logger_.debug("DIGEST:" + object_data_hash);
+ logger_.debug("build digest from data object:end");
+ }
+ return verify_req_str;
+ }
+ catch (UnsupportedEncodingException e)
+ {
+ throw new SignatureException(310, e);
+ }
+ }
+
+ /**
+ * This method generates the MOA verify prozess. It checks if the given
+ * SignatureObject is signed by MOA or BKU. The verify template string is
+ * filled out by the corresponding method.
+ *
+ * @param normalizedText
+ * the normalized text to verify
+ * @param sigObject
+ * the SignatureObject holding the singature values
+ * @return a SignatureResponse object if the verify prozess does not fails
+ * @throws SignatureException
+ * @see SignatureResponse
+ */
+ public SignatureResponse doVerify(String normalizedText,
+ SignatureObject sigObject) throws SignatureException
+ {
+ String verify_url = getVerifyURL(sigObject.getSignationType()); // settings_.getValueFromKey(TYPE
+ // + "." +
+ // Signature.VALUE_MODE_VERIFY
+ // +
+ // ".url");
+ String verify_request = getVerifyRequestTemplateFileName(sigObject.getSignationType()); // settings_.getValueFromKey(TYPE
+ // +
+ // "."
+ // +
+ // Signature.VALUE_MODE_VERIFY
+ // +
+ // ".request");
+ String trust_profile = getVerifyTrustProfileID(sigObject.getSignationType());
+ String verify_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(verify_request));
+
+ String verify_template_str = null;
+ if (sigObject.isMOASigned())
+ {
+ verify_template_str = getVerifyTemplate(normalizedText, sigObject);
+ }
+ else
+ {
+ BKUConnector bku_conn = new BKUConnector();
+ verify_template_str = bku_conn.getVerifyTemplate(normalizedText, sigObject);
+ }
+ verify_req_str = verify_req_str.replaceFirst("XMLContentReplace", verify_template_str);
+ verify_req_str = verify_req_str.replaceFirst("TrustProfileIDReplace", trust_profile);
+
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_req_str);
+ // FileHelper.writeToFile(verify_request + "_request.xml",
+ // verify_req_str);
+ }
+ String response_string = "";
+ try
+ {
+ response_string = MOAConnector.connectMOA(verify_req_str, MOAConnector.SERVICE_VERIFY, verify_url);
+ }
+ catch (WebException we)
+ {
+ if (logger_.isDebugEnabled())
+ {
+ we.printStackTrace();
+ }
+ SignatureException se = new SignatureException(we.getErrorCode(), we);
+ throw se;
+ }
+
+ if (!response_string.equals(""))
+ {
+ Pattern erc_p_s = Pattern.compile("<[\\w]*:?ErrorCode>");
+ Pattern erc_p_e = Pattern.compile("</[\\w]*:?ErrorCode>");
+ Matcher erc_m_s = erc_p_s.matcher(response_string);
+ Matcher erc_m_e = erc_p_e.matcher(response_string);
+
+ if (erc_m_s.find() && erc_m_e.find())
+ {
+ if (logger_.isEnabledFor(Level.ERROR))
+ {
+ //logger_.debug(response_string);
+ // FileHelper.writeToFile(verify_request + "_response.xml",
+ // response_string);
+ logger_.error("Write error response to file:" + verify_request + "_response.xml");
+ }
+ Pattern erm_p_s = Pattern.compile("<[\\w]*:?Info>");
+ Pattern erm_p_e = Pattern.compile("</[\\w]*:?Info>");
+ Matcher erm_m_s = erm_p_s.matcher(response_string);
+ Matcher erm_m_e = erm_p_e.matcher(response_string);
+ SignatureException se = new SignatureException(0, "MOASigExc2");
+ String error_code = response_string.substring(erc_m_s.end(), erc_m_e.start());
+ se.setExternalErrorCode(error_code);
+ if (erm_m_s.find() && erm_m_e.find())
+ {
+ String error_mess = response_string.substring(erm_m_s.end(), erm_m_e.start());
+ se.setExternalErrorMessage(error_mess);
+ }
+ throw se;
+ }
+ else
+ {
+ if (logger_.isDebugEnabled())
+ {
+ //logger_.debug(verify_request + "_response.xml " + response_string);
+ }
+ return parseVerifyXMLResponse(response_string);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * This method parses the verify response string and return a
+ * SignatureResponse object. The SignatureResponse object is filled out by the
+ * response values from the BKU-response.
+ *
+ * @param xmlResponse
+ * the response values from the MOA-verify request
+ * @return SignatureResponse object
+ * @see SignatureResponse
+ */
+ private SignatureResponse parseVerifyXMLResponse(String xmlResponse)
+ {
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Try parsing the verify response");
+ }
+ Pattern sub_nam_p_s = Pattern.compile("<dsig:X509SubjectName>");
+ Pattern sub_nam_p_e = Pattern.compile("</dsig:X509SubjectName>");
+ Pattern iss_nam_p_s = Pattern.compile("<dsig:X509IssuerName>");
+ Pattern iss_nam_p_e = Pattern.compile("</dsig:X509IssuerName>");
+ Pattern ser_num_p_s = Pattern.compile("<dsig:X509SerialNumber>");
+ Pattern ser_num_p_e = Pattern.compile("</dsig:X509SerialNumber>");
+
+ Pattern sig_chk_p_s = Pattern.compile("<SignatureCheck>");
+ Pattern sig_chk_p_e = Pattern.compile("</SignatureCheck>");
+ Pattern man_chk_p_s = Pattern.compile("<SignatureManifestCheck>");
+ Pattern man_chk_p_e = Pattern.compile("</SignatureManifestCheck>");
+ Pattern cer_chk_p_s = Pattern.compile("<CertificateCheck>");
+ Pattern cer_chk_p_e = Pattern.compile("</CertificateCheck>");
+
+ Pattern code_p_s = Pattern.compile("<Code>");
+ Pattern code_p_e = Pattern.compile("</Code>");
+
+ Pattern cert_p_s = Pattern.compile("<dsig:X509Certificate>");
+ Pattern cert_p_e = Pattern.compile("</dsig:X509Certificate>");
+
+ Matcher sub_nam_m_s = sub_nam_p_s.matcher(xmlResponse);
+ Matcher sub_nam_m_e = sub_nam_p_e.matcher(xmlResponse);
+ Matcher iss_nam_m_s = iss_nam_p_s.matcher(xmlResponse);
+ Matcher iss_nam_m_e = iss_nam_p_e.matcher(xmlResponse);
+ Matcher ser_num_m_s = ser_num_p_s.matcher(xmlResponse);
+ Matcher ser_num_m_e = ser_num_p_e.matcher(xmlResponse);
+
+ Matcher sig_chk_m_s = sig_chk_p_s.matcher(xmlResponse);
+ Matcher sig_chk_m_e = sig_chk_p_e.matcher(xmlResponse);
+ Matcher man_chk_m_s = man_chk_p_s.matcher(xmlResponse);
+ Matcher man_chk_m_e = man_chk_p_e.matcher(xmlResponse);
+ Matcher cer_chk_m_s = cer_chk_p_s.matcher(xmlResponse);
+ Matcher cer_chk_m_e = cer_chk_p_e.matcher(xmlResponse);
+
+ Matcher cert_m_s = cert_p_s.matcher(xmlResponse);
+ Matcher cert_m_e = cert_p_e.matcher(xmlResponse);
+
+ SignatureResponse sig_res = new SignatureResponse();
+ if (sub_nam_m_s.find() && sub_nam_m_e.find())
+ {
+ String sub_nam = xmlResponse.substring(sub_nam_m_s.end(), sub_nam_m_e.start());
+ sig_res.setX509SubjectName(sub_nam);
+ }
+ if (iss_nam_m_s.find() && iss_nam_m_e.find())
+ {
+ String iss_nam = xmlResponse.substring(iss_nam_m_s.end(), iss_nam_m_e.start());
+ sig_res.setX509IssuerName(iss_nam);
+ }
+ if (ser_num_m_s.find() && ser_num_m_e.find())
+ {
+ String ser_num = xmlResponse.substring(ser_num_m_s.end(), ser_num_m_e.start());
+ sig_res.setX509SerialNumber(ser_num);
+ }
+ if (sig_chk_m_s.find() && sig_chk_m_e.find())
+ {
+ String sig_chk = xmlResponse.substring(sig_chk_m_s.end(), sig_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(sig_chk);
+ Matcher code_m_e = code_p_e.matcher(sig_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = sig_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setSignatureCheckCode(code);
+ }
+ }
+ if (man_chk_m_s.find() && man_chk_m_e.find())
+ {
+ String man_chk = xmlResponse.substring(man_chk_m_s.end(), man_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(man_chk);
+ Matcher code_m_e = code_p_e.matcher(man_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = man_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setSignatureManifestCheckCode(code);
+ }
+ }
+ if (cer_chk_m_s.find() && cer_chk_m_e.find())
+ {
+ String cer_chk = xmlResponse.substring(cer_chk_m_s.end(), cer_chk_m_e.start());
+ Matcher code_m_s = code_p_s.matcher(cer_chk);
+ Matcher code_m_e = code_p_e.matcher(cer_chk);
+ if (code_m_s.find() && code_m_e.find())
+ {
+ String code = cer_chk.substring(code_m_s.end(), code_m_e.start());
+ sig_res.setCertificateCheckCode(code);
+ }
+ }
+ if (cert_m_s.find() && cert_m_e.find())
+ {
+ String cert_string = xmlResponse.substring(cert_m_s.end(), cert_m_e.start());
+
+ X509Cert resp_cert = X509Cert.initByString(cert_string);
+ sig_res.setCertificate(resp_cert);
+ }
+
+ return sig_res;
+ }
+
+ protected String getConnectorValueFromProfile(String profile, String key)
+ {
+ String value = settings_.getValueFromKey("sig_obj." + profile + "." + key);
+ if (value == null)
+ {
+ value = settings_.getValueFromKey(key);
+ }
+ return value;
+ }
+
+ public String getSignURL(String profile)
+ {
+ final String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".url";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSignRequestTemplateFileName(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".request";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSignKeyIdentifier(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".KeyIdentifier";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ public String getVerifyURL(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".url";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getVerifyRequestTemplateFileName(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".request";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getVerifyTemplateFileName(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".template";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getSigPropFileName(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".template.SP";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ protected String getVerifyTrustProfileID(String profile)
+ {
+ String key = TYPE + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".TrustProfileID";
+ return getConnectorValueFromProfile(profile, key);
+ }
+
+ /**
+ * This method connects the moa server getting the requestString, the given
+ * serviseMode and the endpointUrl. The requestString is the envelope of the
+ * SOAP Message send and recieve by the AXIS module. The Response SOAP message
+ * of the MOA server is parsed by AXIS and the message envelope is send back
+ * to the calling method.
+ *
+ * @param requestString
+ * the request string (XML) to send.
+ * @param serviceMode
+ * the mode which connect to MOA
+ * @param endpointURL
+ * the URL which the MOA server is running
+ * @return the response string (XML) of the MOA server
+ * @throws WebException
+ */
+ public static String connectMOA(String requestString, String serviceMode,
+ String endpointURL) throws WebException
+ {
+ try
+ {
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info(serviceMode);
+ logger_.info(endpointURL);
+ }
+ // Parser/DOMBuilder instanzieren
+ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setNamespaceAware(true);
+ DocumentBuilder builder = factory.newDocumentBuilder();
+
+ // XML Datei in einen DOM-Baum umwandeln
+ ByteArrayInputStream bais = new ByteArrayInputStream(requestString.getBytes("UTF-8"));
+ Document xmlRequest = builder.parse(bais);
+
+ // Call öffnen
+ Call call = null;
+
+ // Neues BodyElement anlegen und mit dem DOM-Baum füllen
+ SOAPBodyElement body = new SOAPBodyElement(xmlRequest.getDocumentElement());
+ SOAPBodyElement[] params = new SOAPBodyElement[] { body };
+
+ // AXIS-Server instanzieren
+ Service service = ServiceFactory.newInstance().createService(new QName(serviceMode));
+ call = service.createCall();
+ call.setTargetEndpointAddress(endpointURL);
+
+ // Call auslösen und die Antworten speichern
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Calling MOA:" + endpointURL);
+ }
+ Vector responses = (Vector) call.invoke(params);
+
+ // Erstes Body Element auslesen
+ SOAPBodyElement response = (SOAPBodyElement) responses.get(0);
+
+ // Aus der Response den DOM-Baum lesen
+ Document root_response = response.getAsDocument();
+ if (logger_.isInfoEnabled())
+ {
+ logger_.info("Return from MOA:" + serviceMode);
+ }
+
+ // XML-Formatierung konfiguieren
+ OutputFormat format = new OutputFormat((Document) root_response);
+ format.setLineSeparator("\n");
+ format.setIndenting(false);
+ format.setPreserveSpace(true);
+ format.setOmitXMLDeclaration(false);
+ format.setEncoding("UTF-8");
+
+ // Ausgabe der Webservice-Antwort auf die Konsole
+ // XMLSerializer conSerializer = new XMLSerializer(System.out, format);
+ // conSerializer.serialize(root_response);
+
+ // Ausgabe der Webservice-Antwort in Datei
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ XMLSerializer response_serializer = new XMLSerializer(baos, format);
+ response_serializer.serialize(root_response);
+ return baos.toString("UTF-8");
+ }
+ catch (Exception e)
+ {
+ throw new WebException(330, e);
+ }
+ // serialize signature only
+
+ // if
+ // (root_response.getDocumentElement().getLocalName().equals("CreateXMLSignatureResponse"))
+ // {
+ // Element signature = (Element)
+ // root_response.getElementsByTagNameNS("http://www.w3.org/2000/09/xmldsig#",
+ // "Signature").item(0);
+ // String signatureFile = getProperty(mode + "Request").substring(0,
+ // getProperty(mode +
+ // "Request").lastIndexOf('.')) + ".Signature.xml";
+ // fileSerializer = new XMLSerializer(new FileOutputStream(signatureFile),
+ // format);
+ // fileSerializer.serialize(signature);
+ // }
+
+ }
+} \ No newline at end of file