From 8e3ed85168edaeadcd4f3ec92450036a399d6ede Mon Sep 17 00:00:00 2001 From: knowcenter Date: Sat, 12 May 2007 17:37:16 +0000 Subject: Detached Multipart BKU for Auftrag "Support" git-svn-id: https://joinup.ec.europa.eu/svn/pdf-as/trunk@73 7b5415b0-85f9-ee4d-85bd-d5d0c3b42d1c --- .../test/at/knowcenter/wag/egov/egiz/TestNeu.java | 265 ++++++ .../wag/egov/egiz/detached/BKUConnector.java | 987 +++++++++++++++++++++ .../wag/egov/egiz/detached/BKUPostConnection.java | 230 +++++ .../wag/egov/egiz/detached/MOAConnector.java | 869 ++++++++++++++++++ 4 files changed, 2351 insertions(+) create mode 100644 src/test/java/test/at/knowcenter/wag/egov/egiz/TestNeu.java create mode 100644 src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUConnector.java create mode 100644 src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUPostConnection.java create mode 100644 src/test/java/test/at/knowcenter/wag/egov/egiz/detached/MOAConnector.java (limited to 'src/test/java') diff --git a/src/test/java/test/at/knowcenter/wag/egov/egiz/TestNeu.java b/src/test/java/test/at/knowcenter/wag/egov/egiz/TestNeu.java new file mode 100644 index 0000000..84fda4c --- /dev/null +++ b/src/test/java/test/at/knowcenter/wag/egov/egiz/TestNeu.java @@ -0,0 +1,265 @@ +/** + * + */ +package test.at.knowcenter.wag.egov.egiz; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.UnsupportedEncodingException; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.PropertyConfigurator; + +import test.at.knowcenter.wag.egov.egiz.detached.BKUConnector; +import test.at.knowcenter.wag.egov.egiz.detached.MOAConnector; +import at.knowcenter.wag.egov.egiz.PdfASID; +import at.knowcenter.wag.egov.egiz.cfg.SettingsReader; +import at.knowcenter.wag.egov.egiz.exceptions.SignatureException; +import at.knowcenter.wag.egov.egiz.sig.SignatureData; +import at.knowcenter.wag.egov.egiz.sig.SignatureObject; +import at.knowcenter.wag.egov.egiz.sig.SignatureResponse; +import at.knowcenter.wag.egov.egiz.sig.connectors.bku.DetachedMultipartBKUConnector; +import at.knowcenter.wag.egov.egiz.sig.connectors.bku.SignSignatureObject; +import at.knowcenter.wag.egov.egiz.tools.FileHelper; + +/** + * @author wprinz + * + */ +public class TestNeu +{ + private static Log logger = LogFactory.getLog(TestNeu.class); + + protected static String TEXT = "Test 123 äöüß"; //$NON-NLS-1$ + + protected static File PDF = new File("C:\\wprinz\\Filer\\egiz\\docs\\document4.pdf"); //$NON-NLS-1$ + + + /** + * @param args + * @throws SignatureException + */ + public static void main(String[] args) throws Exception + { + SettingsReader.initializeForCommandLine(); + PropertyConfigurator.configure(SettingsReader.CONFIG_PATH + "log4j.properties"); //$NON-NLS-1$ + + testDetachedMultipartBKUConnector(); + + // testTexMOA(); + + // testBinBKU(); + + // testTexBKU(); + + // SignatureResponse sr = bku_c.doVerify(TEXT, so); + + // logger.debug("sr = " + sr); + + logger.info("finished."); + } + + public static void testDetachedMultipartBKUConnector() throws Exception + { + DetachedMultipartBKUConnector c = new DetachedMultipartBKUConnector("CIO-BUND2"); //$NON-NLS-1$ + + SignatureData data = new BinarySignatureData(); + + SignSignatureObject so = c.doSign(data); + + FileOutputStream fos = new FileOutputStream("C:\\wprinz\\Filer\\egiz2\\SignatureObject.bin"); + ObjectOutputStream oos = new ObjectOutputStream(fos); + oos.writeObject(so); + oos.close(); + + FileInputStream fis = new FileInputStream("C:\\wprinz\\Filer\\egiz2\\SignatureObject.bin"); + ObjectInputStream ois = new ObjectInputStream(fis); + so = (SignSignatureObject) ois.readObject(); + ois.close(); + + SignatureResponse sr = c.doVerify(data, so); + logger.debug("sr = " + sr); + + } + + public static void testBinBKU() throws Exception + { + FileInputStream fis = new FileInputStream(PDF); + byte[] data = new byte[(int) PDF.length()]; + fis.read(data); + fis.close(); + + PdfASID algorithm = new PdfASID("urn:pdfsigfilter:bka.gv.at:binaer:v1.0.0"); + + SignatureObject so = testSignBKU(data, algorithm); + + so.setKZ(algorithm); + + SignatureResponse sr = testVerifyBKU(data, so); + + logger.debug("sr = " + sr); + + } + + public static void testTexBKU() throws Exception + { + PdfASID algorithm = new PdfASID("urn:pdfsigfilter:bka.gv.at:text:v1.0.0"); + + SignatureObject so = testSignBKU(TEXT.getBytes("UTF-8"), algorithm); + + so.setKZ(algorithm); + + // FileOutputStream fos = new + // FileOutputStream("C:\\wprinz\\Filer\\egiz2\\SignatureObject.bin"); + // ObjectOutputStream oos = new ObjectOutputStream(fos); + // oos.writeObject(so); + // oos.close(); + + SignatureResponse sr = testVerifyBKU(TEXT.getBytes("UTF-8"), so); + + logger.debug("sr = " + sr); + } + + public static void testTexMOA() throws Exception + { + PdfASID algorithm = new PdfASID("urn:pdfsigfilter:bka.gv.at:text:v1.0.0"); + + SignatureObject so = testSignMOA(TEXT.getBytes("UTF-8"), algorithm); + + so.setKZ(algorithm); + + // FileOutputStream fos = new + // FileOutputStream("C:\\wprinz\\Filer\\egiz2\\SignatureObject.bin"); + // ObjectOutputStream oos = new ObjectOutputStream(fos); + // oos.writeObject(so); + // oos.close(); + + // SignatureResponse sr = testVerifyBKU(TEXT.getBytes("UTF-8"), so); + // + // logger.debug("sr = " + sr); + } + + public static SignatureObject testSignBKU(byte[] data, PdfASID algorithm) throws Exception + { + BKUConnector bku_c = new BKUConnector(); + + SignatureObject so = bku_c.doSign("CIO-BUND2", data, algorithm); + + logger.debug("so = " + so); + + return so; + } + + public static SignatureObject testSignMOA(byte[] data, PdfASID algorithm) throws Exception + { + MOAConnector moa_c = new MOAConnector(); + + SignatureObject so = moa_c.doSign("CIO-BUND2", data, algorithm); + + logger.debug("so = " + so); + + return so; + } + + public static SignatureResponse testVerifyBKU(byte[] data, SignatureObject so) throws Exception + { + BKUConnector bku_c = new BKUConnector(); + + SignatureResponse sr = bku_c.doVerify(data, so); + + logger.debug("sr = " + sr); + + return sr; + } + + /** + * A data source for text data. + * + * @author wprinz + */ + public static class TextSignatureData implements SignatureData + { + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getData() + */ + public byte[] getData() + { + try + { + return TEXT.getBytes(getCharacterEncoding()); + } + catch (UnsupportedEncodingException e) + { + e.printStackTrace(); + return null; + } + } + + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getMimeType() + */ + public String getMimeType() + { + return "text/plain"; //$NON-NLS-1$ + } + + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getCharacterEncoding() + */ + public String getCharacterEncoding() + { + return "UTF-8"; //$NON-NLS-1$ + } + } + + /** + * A data source for binary (PDF) data. + * + * @author wprinz + */ + public static class BinarySignatureData implements SignatureData + { + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getData() + */ + public byte[] getData() + { + try + { + FileInputStream fis = new FileInputStream(PDF); + byte[] data = new byte[(int) PDF.length()]; + fis.read(data); + fis.close(); + + return data; + } + catch (Exception e) + { + e.printStackTrace(); + return null; + } + } + + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getMimeType() + */ + public String getMimeType() + { + return "application/pdf"; //$NON-NLS-1$ + } + + /** + * @see at.knowcenter.wag.egov.egiz.sig.SignatureData#getCharacterEncoding() + */ + public String getCharacterEncoding() + { + return null; + } + + } + +} diff --git a/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUConnector.java b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUConnector.java new file mode 100644 index 0000000..d395de5 --- /dev/null +++ b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUConnector.java @@ -0,0 +1,987 @@ +/* + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * 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 test.at.knowcenter.wag.egov.egiz.detached; + +import java.io.FileOutputStream; +import java.io.OutputStreamWriter; +import java.io.UnsupportedEncodingException; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.log4j.Level; +import org.apache.log4j.Logger; + +import java.io.File; +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.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.framework.SignatorFactory; +import at.knowcenter.wag.egov.egiz.sig.X509Cert; +import at.knowcenter.wag.egov.egiz.sig.connectors.ConnectorConfigurationKeys; +import at.knowcenter.wag.egov.egiz.sig.connectors.MOAConnector; +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 +{ + /** + * 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); + } + } + } + + public SignatureObject doSign(String sigType, byte[] data, PdfASID algorithm) throws SignatureException + { + String sigmode = algorithm.getType(); + + String request_string = prepareSignRequestDetached(sigType, sigmode); + + String sign_url = getSignURL(sigType); + + String versionstring = algorithm.getVersion(); + logger_.info("versionstring=" + versionstring); + + String mimetype = ""; + if (sigmode.equalsIgnoreCase(SignatorFactory.TYPE_TEXTUAL)) + { + mimetype = "text/plain"; + } + if (sigmode.equalsIgnoreCase(SignatorFactory.TYPE_BINARY)) + { + mimetype = "application/pdf"; + } + + Properties response_properties = sendRequest(sign_url, request_string, data, mimetype); + + return analyzeSignResponse(response_properties, sigType); + } + + public SignatureResponse doVerify(byte[] data, SignatureObject sigObject) throws SignatureException + { + String sigmode = sigObject.getKZ().getType(); + String sigversion = sigObject.getKZ().getVersion(); + + // decide which template should be used to verify + // use versionstring to decide if detached Signature + String request_string = prepareVerifyRequestDetached(data, sigObject); + // if (sigversion.equals(SignatorFactory.VERSION_1_1_0)) + // { + // TODO support Sign v1.1.0 Remove base64 and write tempfile + // String sigversion=SignatorFactory.TYPE_TEXTUAL; + + String mimetype = ""; + if (sigmode.equalsIgnoreCase(SignatorFactory.TYPE_TEXTUAL)) + { + mimetype = "text/plain"; + } + if (sigmode.equalsIgnoreCase(SignatorFactory.TYPE_BINARY)) + { + mimetype = "application/pdf"; + } + + String verify_url = getVerifyURL(sigObject.getSignationType()); + Properties response_properties = sendRequest(verify_url, request_string, data, mimetype); + + return analyzeVerifyResponse(response_properties); + } + + /** + * 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(Properties response_properties, + SignatureObject sigObj) throws SignatureException + { + String xmlResponse = response_properties.getProperty("response_string"); + + Pattern sig_val_p_s = Pattern.compile("<[\\w]*:?SignatureValue>"); + Pattern sig_val_p_e = Pattern.compile(""); + Pattern iss_nam_p_s = Pattern.compile("<[\\w]*:?X509IssuerName>"); + Pattern iss_nam_p_e = Pattern.compile(""); + Pattern sig_tim_p_s = Pattern.compile("<[\\w]*:?SigningTime>"); + Pattern sig_tim_p_e = Pattern.compile(""); + Pattern ser_num_p_s = Pattern.compile("<[\\w]*:?X509SerialNumber>"); + Pattern ser_num_p_e = Pattern.compile(""); + Pattern sig_cer_p_s = Pattern.compile("<[\\w]*:?X509Certificate>"); + Pattern sig_cer_p_e = Pattern.compile(""); + + Pattern sig_cer_d_p_s = Pattern.compile("<[\\w]*:?CertDigest>"); + Pattern sig_cer_d_p_e = Pattern.compile(""); + Pattern dig_val_p_s = Pattern.compile("<[\\w]*:?DigestValue>"); + Pattern dig_val_p_e = Pattern.compile(""); + + 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-"); + String final_ids = formatSigIds(ids); + sigObj.setSignationIDs(final_ids); + } + + protected String formatSigIds(String[] sigIds) throws SignatureException + { + // ids algorithm: + 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); + if (cur_id.equalsIgnoreCase("")) + { + cur_id = "0"; + } + + join += "-" + cur_id; + } + String ids = base + "@" + join.substring(1); + String final_ids = getSigIDprefixValueFromProfile() + ids; + return final_ids; + } + + protected String getSigIDprefixValueFromProfile() + { + String key = getType() + ".sign.SIG_IDprefix"; + String value = settings_.getValueFromKey(key); + if (value == null) + { + value = ""; + } + return value; + } + + /** + * 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); + + final int quot_end_idx = end_idx; + final int squot_end_idx = text.indexOf("'", start_idx); + end_idx = Math.min(quot_end_idx, squot_end_idx); + id = text.substring(start_idx, end_idx); + logger_.info("extract id:" + name + id); + if (logger_.isDebugEnabled()) + { + logger_.debug("extract id:" + name + id); + } + return id; + } + + public String getVerifyTemplate(byte [] data, + SignatureObject sigObject) throws SignatureException + { + // TODO Template selection depending on Sigid + try + { + if (data == null) + { + SignatureException se = new SignatureException(311, "Document can not be verified because data 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 = "./templates/BKUVerifyTemplateDetached.xml";//getVerifyTemplateFileName(sigObject.getSignationType()); + String sigmode = sigObject.getKZ().getType(); + + String sig_prop_filename = "./templates/BKUVerifyTemplateSP_neueBKU_text.xml"; //getSigPropFileName(sigObject.getSignationType(), sigmode); + + if (sigObject.getKZ().getType().equals("binaer")) + { + sig_prop_filename = "./templates/BKUVerifyTemplateSP_neueBKU_bin.xml"; + } + + + logger_.info(" verify_template= " + verify_template); + logger_.info("sig_prop_filename = " + sig_prop_filename); + String ids_string = sigObject.getSignationIds(); + logger_.info("ids_string = " + ids_string); + String[] ids = SignatureObject.parseSigIds(ids_string); + + // TODO hotfix + boolean neue_bku = true; + if (ids[5] != null) + { + // Hash has to be made over an other part than in previous versions. + // i dont know how this is in newer versions than 2.7.1 + // id[5] of Signature of 2.7.1 signed Pdfs is "etsi-bka-1.0@" + if (ids[5].equals("etsi-bka-1.0@")) + { + neue_bku = true; + } + } + logger_.info("verify ids[5] = " + ids[5]); + logger_.info("verify neue_bku = " + neue_bku); + if (neue_bku) + { + // verify_template = + // getConnectorValueFromProfile(sigObject.getSignationType(), + // "bku.verify.template2"); + // //"./templates/BKUVerifyTemplateB64_neueBKU.xml"; + // sig_prop_filename = + // getConnectorValueFromProfile(sigObject.getSignationType(), + // "bku.verify.template2.SP"); + // //"./templates/BKUVerifyTemplateSP_neueBKU.xml"; + } + + 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"); + } + + 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); + logger_.info("XXXXXSignedPropertiesoldbase64bku sig_prop_hash=" + sig_prop_hash); + // TODO hotfix + // if (neue_bku) + // { + // BKU Version 2.7.1 builds hash over other than previous + final String ETSI_SIGNED_PROPERTIES_START_TAG = "= 0; + final int hash_end = sig_prop_str.indexOf(ETSI_SIGNED_PROPERTIES_END_TAG, hash_start) + ETSI_SIGNED_PROPERTIES_END_TAG.length(); + assert hash_end - ETSI_SIGNED_PROPERTIES_END_TAG.length() >= 0; + assert hash_end > hash_start; + + final String string_to_be_hashed = sig_prop_str.substring(hash_start, hash_end); + logger_.info("etsi:SignedProperties string to be hashed: " + string_to_be_hashed); + + final byte[] bytes_to_be_hashed = string_to_be_hashed.getBytes("UTF-8"); + sig_prop_code = CodingHelper.buildDigest(bytes_to_be_hashed); + sig_prop_hash = CodingHelper.encodeBase64(sig_prop_code); + logger_.info("XXXXXSignedPropertiesnewbase64bku sig_prop_hash=" + sig_prop_hash); + // } + + ver_temp_str = ver_temp_str.replaceFirst("DigestValueSignedPropertiesReplace", sig_prop_hash); + // logger_.info("DIGEST:" + 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 = data; // normalizedText.getBytes("UTF-8"); + byte[] data_value_hash = CodingHelper.buildDigest(data_value); + String object_data_hash = CodingHelper.encodeBase64(data_value_hash); + // logger_.info("XXXXXXxbase64 object_data_hash="+object_data_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(""); + Pattern sub_nam_p_e = Pattern.compile(""); + Pattern iss_nam_p_s = Pattern.compile(""); + Pattern iss_nam_p_e = Pattern.compile(""); + Pattern ser_num_p_s = Pattern.compile(""); + Pattern ser_num_p_e = Pattern.compile(""); + + Pattern sig_chk_p_s = Pattern.compile(""); + Pattern sig_chk_p_e = Pattern.compile(""); + Pattern man_chk_p_s = Pattern.compile(""); + Pattern man_chk_p_e = Pattern.compile(""); + Pattern cer_chk_p_s = Pattern.compile(""); + Pattern cer_chk_p_e = Pattern.compile(""); + + // [tknall] start qualified certificate + Pattern cert_qualified_p = Pattern.compile(""); + Matcher cert_qualified_m = cert_qualified_p.matcher(xmlResponse); + // [tknall] stop qualified certificate + + Pattern code_p_s = Pattern.compile(""); + Pattern code_p_e = Pattern.compile(""); + Pattern info_p_s = Pattern.compile(""); + Pattern info_p_e = Pattern.compile(""); + + Pattern cert_p_s = Pattern.compile(""); + Pattern cert_p_e = Pattern.compile(""); + + 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(); + + // [tknall] start qualified certificate + sig_res.setQualifiedCertificate(cert_qualified_m.find()); + // [tknall] stop qualified certificate + + 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 prepareSignRequestDetached(String signType, String sigmode) throws SignatureException + { + logger_.info("Call " + getType() + " connector sigmode=" + sigmode); + + String keybox_identifier = getSignKeyboxIdentifier(signType); + String sign_request_filename = getSignRequestTemplateFileName(signType, sigmode); + String sign_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(sign_request_filename)); + + if (sign_req_str == null) + { + throw new SignatureException(300, "Can not read the create xml request template"); + } + sign_req_str = sign_req_str.replaceFirst("KeyboxIdentifierReplace", keybox_identifier); + return sign_req_str; + } + + // decides if moasigned or BKU + public String prepareVerifyRequestDetached(byte[] data, + SignatureObject sigObject) throws SignatureException + { + // get templates + String verify_request = "./templates/BKUVerifyRequestDetached.xml"; //getVerifyRequestTemplateFileName(sigObject.getSignationType()); + String verify_req_str = FileHelper.readFromFile(SettingsReader.relocateFile(verify_request)); + logger_.info("prepareVerifyRequest TemplateFile=" + verify_request); + + String verify_template_str = null; + // TODO implement MOA +// 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(data, sigObject); +// } + + verify_req_str = verify_req_str.replaceFirst("XMLContentReplace", verify_template_str); + if (logger_.isDebugEnabled()) + { + logger_.debug("verify_req_str.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 Properties sendRequest(String url, String request_string) throws SignatureException + { + try + { + Properties response_properties = BKUPostConnection.doPostRequest(url, request_string); + return response_properties; + } + catch (Exception e) + { + SignatureException se = new SignatureException(320, e); + throw se; + } + } + + /** + * + * @param url + * The URL. + * @param request_string + * The request string. + * @return Returns the response string. + * @throws SignatureException + * F.e. + */ + protected Properties sendRequest(String url, String request_string, + byte[] signdata, String mimetype) throws SignatureException + { + try + { + // Properties response_properties = + // BKUPostConnection.doPostRequest272(url, request_string, signdata, + // mimetype); + Properties response_properties = BKUPostConnection.doPostRequest272(url, request_string, signdata, mimetype); + return response_properties; + } + catch (Exception e) + { + SignatureException se = new SignatureException(320, e); + throw se; + } + } + + public SignatureObject analyzeSignResponse(Properties response_properties, + String sigType) throws SignatureException + { + // String sign_request_filename = getSignRequestTemplateFileName(sigType); + + // TODO hotfix + String response_string = response_properties.getProperty("response_string"); + + // TODO debug + try + { + FileOutputStream fos = new FileOutputStream("C:\\wprinz\\Filer\\egiz2\\sign_response.utf8.xml"); + OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8"); + osw.write(response_string); + osw.close(); + } + catch (Exception e) + { + logger_.error(e); + } + + 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(""); + 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(""); + 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("signature_response_string: " + response_string); + } + parseCreateXMLResponse(response_properties, sig_obj); + } + } + sig_obj.setSigResponse(response_string); + return sig_obj; + } + + public SignatureResponse analyzeVerifyResponse(Properties response_properties) throws SignatureException + { + String response_string = response_properties.getProperty("response_string"); + + if (!response_string.equals("")) + { + Pattern erc_p_s = Pattern.compile("<[\\w]*:?ErrorCode>"); + Pattern erc_p_e = Pattern.compile(""); + 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(""); + 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 sigmode) + { + String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_SIGN + ".request" + "." + sigmode; + logger_.info("getSignRequestTemplateFileName: profile=" + profile + "" + " key=" + key); + String filename = getConnectorValueFromProfile(profile, key); + logger_.info("getSignRequestTemplateFileName filename=" + filename); + return filename;// 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 sigmode) + { + String key = getType() + "." + ConnectorConfigurationKeys.VALUE_MODE_VERIFY + ".template.SP." + sigmode; + logger_.info("getSigPropFileName: profile=" + profile + "" + " key=" + key); + String filename = getConnectorValueFromProfile(profile, key); + logger_.info("getSigPropFileName filename=" + filename); + return getConnectorValueFromProfile(profile, key); + } + + /** + * Returns the type of this BKU-like connector. + * + *

+ * 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. + *

+ * + * @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/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUPostConnection.java b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUPostConnection.java new file mode 100644 index 0000000..0c219b8 --- /dev/null +++ b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/BKUPostConnection.java @@ -0,0 +1,230 @@ +/** + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * 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 test.at.knowcenter.wag.egov.egiz.detached; + +import java.io.IOException; +import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.apache.commons.httpclient.Header; +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.methods.multipart.ByteArrayPartSource; +import org.apache.commons.httpclient.methods.multipart.FilePart; +import org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity; +import org.apache.commons.httpclient.methods.multipart.Part; +import org.apache.commons.httpclient.methods.multipart.StringPart; +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 Properties doPostRequest272(String url, String request, + byte[] signdata, String mimetype) throws HttpException, IOException + { + // // TODO remove write request to File + // FileOutputStream fos = new + // FileOutputStream("F:\\PDFAS_SVN\\trunk\\work\\pdfastmp\\bku_request.xml"); + // fos.write(request.getBytes("UTF-8")); + // fos.close(); + + StringPart xmlpart = new StringPart("XmlRequest", request, "UTF-8"); + xmlpart.setContentType(null); + xmlpart.setTransferEncoding(null); + // BKU 2.7.4 can't handle the Content-Type Header for the XML + // xmlpart.setContentType("text/xml"); + // xmlpart.setTransferEncoding(null); + + String filename = mimetype.equals("application/pdf") ? "myfile.pdf" : "myfile.txt"; + ByteArrayPartSource baps = new ByteArrayPartSource(filename, signdata); + // FilePart fpart = new FilePart("fileupload",signdata.getName(), signdata); + FilePart filepart = new FilePart("fileupload", baps); + filepart.setContentType(mimetype); + + // Part[] parts = {fpart, xmlrequest}; + Part[] parts = { xmlpart, filepart }; + + HttpMethodParams method_params = new HttpMethodParams(); + method_params.setContentCharset("UTF-8"); + + PostMethod post_method = new PostMethod(url); + post_method.setParams(method_params); + + MultipartRequestEntity mprqe = new MultipartRequestEntity(parts, post_method.getParams()); + post_method.setRequestEntity(mprqe); + + HttpClient http_client = new HttpClient(); + int method_response = http_client.executeMethod(post_method); + logger_.debug("method_response = " + method_response); + + Properties response_properties = new Properties(); + + if (logger_.isDebugEnabled()) + { + Header[] response_headers = post_method.getResponseHeaders(); + for (int i = 0; i < response_headers.length; i++) + { + logger_.debug(" response_header[" + i + "]: name = " + response_headers[i].getName() + ", value = " + response_headers[i].getValue()); + } + } + // Header server_header = post_method.getResponseHeader("Server"); + + // TODO does BKU really send Content-Type Header + logger_.debug(post_method.getResponseCharSet()); + if (!post_method.getResponseCharSet().equals("UTF-8")) + { + logger_.error("BKU response charset is not UTF-8!"); + } + String response_string = post_method.getResponseBodyAsString(); + +// byte[] response_body = post_method.getResponseBody(); +// String response_string = new String(response_body, "UTF-8"); + + response_properties.setProperty("response_string", response_string); + + return response_properties; + } + + /** + * 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 Properties 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); + + Properties response_properties = new Properties(); + + if (logger_.isDebugEnabled()) + { + Header[] response_headers = post_method.getResponseHeaders(); + logger_.debug("#" + response_headers.length + " headers in response:"); + for (int i = 0; i < response_headers.length; i++) + { + logger_.debug(" response_header[" + i + "]: name = " + response_headers[i].getName() + ", value = " + response_headers[i].getValue()); + } + } + + Header server_header = post_method.getResponseHeader("Server"); + logger_.debug("server_header: name = " + server_header.getName() + ", value = " + server_header.getValue()); + parseBKUVersion(server_header.getValue(), response_properties); + + 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(); + + response_properties.setProperty("response_string", response_string); + + return response_properties; + } + + // TODO hotfix + public static void parseBKUVersion(String header_value, Properties properties) + { + Pattern pattern = Pattern.compile("^citizen-card-environment/(\\d+\\.\\d+) (.+)/(\\d+\\.\\d+\\.\\d+)$"); + Matcher m = pattern.matcher(header_value); + + m.matches(); + + logger_.debug("group count = " + m.groupCount()); + + for (int i = 0; i <= m.groupCount(); i++) + { + logger_.debug(" group[" + i + "] = " + m.group(i)); + } + + final String cceVersion = m.group(1); + final String productName = m.group(2); + final String productVersion = m.group(3); + + logger_.debug("cceVersion = " + cceVersion); + logger_.debug("productName = " + productName); + logger_.debug("productVersion = " + productVersion); + + properties.setProperty("cceVersion", cceVersion); + properties.setProperty("productName", productName); + properties.setProperty("productVersion", productVersion); + } +} diff --git a/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/MOAConnector.java b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/MOAConnector.java new file mode 100644 index 0000000..e6df790 --- /dev/null +++ b/src/test/java/test/at/knowcenter/wag/egov/egiz/detached/MOAConnector.java @@ -0,0 +1,869 @@ +/* + * Copyright (c) 2006 by Know-Center, Graz, Austria + * + * 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 test.at.knowcenter.wag.egov.egiz.detached; + +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.PdfASID; +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.sig.connectors.ConnectorConfigurationKeys; +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 +{ + /** + * 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. + * + *

+ * Just for convenience. + *

+ */ + 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); + } + } + } + + public SignatureObject doSign(String sigType, byte [] data, PdfASID algorithm) 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()); + } + + String url = getSignURL(sigType); + + String sign_request_filename = "./templates/MOASignRequestDetached.xml";//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(""); + Pattern erc_p_e = Pattern.compile(""); + 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(""); + Pattern erm_p_e = Pattern.compile(""); + 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("response_string = " + 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(""); + Pattern iss_nam_p_s = Pattern.compile("<[\\w]*:?X509IssuerName>"); + Pattern iss_nam_p_e = Pattern.compile(""); + Pattern sig_tim_p_s = Pattern.compile("<[\\w]*:?SigningTime>"); + Pattern sig_tim_p_e = Pattern.compile(""); + Pattern ser_num_p_s = Pattern.compile("<[\\w]*:?X509SerialNumber>"); + Pattern ser_num_p_e = Pattern.compile(""); + Pattern sig_cer_p_s = Pattern.compile("<[\\w]*:?X509Certificate>"); + Pattern sig_cer_p_e = Pattern.compile(""); + + Pattern sig_cer_d_p_s = Pattern.compile("<[\\w]*:?CertDigest>"); + Pattern sig_cer_d_p_e = Pattern.compile(""); + Pattern dig_val_p_s = Pattern.compile("<[\\w]*:?DigestValue>"); + Pattern dig_val_p_e = Pattern.compile(""); + + 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(""); +// 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(""); +// 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(""); +// Pattern sub_nam_p_e = Pattern.compile(""); +// Pattern iss_nam_p_s = Pattern.compile(""); +// Pattern iss_nam_p_e = Pattern.compile(""); +// Pattern ser_num_p_s = Pattern.compile(""); +// Pattern ser_num_p_e = Pattern.compile(""); +// +// // [tknall] start qualified certificate +// Pattern cert_qualified_p = Pattern.compile(""); +// Matcher cert_qualified_m = cert_qualified_p.matcher(xmlResponse); +// // [tknall] stop qualified certificate +// +// Pattern sig_chk_p_s = Pattern.compile(""); +// Pattern sig_chk_p_e = Pattern.compile(""); +// Pattern man_chk_p_s = Pattern.compile(""); +// Pattern man_chk_p_e = Pattern.compile(""); +// Pattern cer_chk_p_s = Pattern.compile(""); +// Pattern cer_chk_p_e = Pattern.compile(""); +// +// Pattern code_p_s = Pattern.compile(""); +// Pattern code_p_e = Pattern.compile(""); +// +// Pattern cert_p_s = Pattern.compile(""); +// Pattern cert_p_e = Pattern.compile(""); +// +// 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(); +// +// // [tknall] start qualified certificate +// sig_res.setQualifiedCertificate(cert_qualified_m.find()); +// // [tknall] stop qualified certificate +// +// 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 -- cgit v1.2.3