diff options
author | Andreas Fitzek <andreas.fitzek@iaik.tugraz.at> | 2013-12-11 12:04:19 +0100 |
---|---|---|
committer | Andreas Fitzek <andreas.fitzek@iaik.tugraz.at> | 2013-12-11 12:04:19 +0100 |
commit | 05bb51dd0190c56f7ec59f6f0c759e00f1d72edc (patch) | |
tree | 0c49fa461cc659b335f6e2979d53954d599c6988 | |
parent | 84553d9bc5eb670ee6f9cf21b3f9aa516530bc56 (diff) | |
download | pdf-as-4-05bb51dd0190c56f7ec59f6f0c759e00f1d72edc.tar.gz pdf-as-4-05bb51dd0190c56f7ec59f6f0c759e00f1d72edc.tar.bz2 pdf-as-4-05bb51dd0190c56f7ec59f6f0c759e00f1d72edc.zip |
Signature profile implementations
12 files changed, 329 insertions, 104 deletions
diff --git a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/IProfileConstants.java b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/IProfileConstants.java index 897ced8e..4ebcc019 100644 --- a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/IProfileConstants.java +++ b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/IProfileConstants.java @@ -64,4 +64,6 @@ public interface IProfileConstants { public final static String TMP_DIR = "default.pdfastmp_dir"; public final static String TMP_DIR_DEFAULT_VALUE = "pdfastmp"; + + public final static String SIGNING_REASON = "adobeSignReasonValue"; } diff --git a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/Settings.java b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/Settings.java index da946215..f3e17ab8 100644 --- a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/Settings.java +++ b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/Settings.java @@ -47,9 +47,9 @@ public class Settings implements ISettings, IProfileConstants{ } logger.debug("Configured Properties:"); - if(logger.isDebugEnabled()) { + /*if(logger.isDebugEnabled()) { properties.list(System.out); - } + }*/ } catch (IOException e) { throw new PdfAsSettingsException("Failed to read settings!", e); diff --git a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/SignatureProfileSettings.java b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/SignatureProfileSettings.java index 46f2ed09..ff5e5d29 100644 --- a/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/SignatureProfileSettings.java +++ b/pdf-as-common/src/main/java/at/gv/egiz/pdfas/common/settings/SignatureProfileSettings.java @@ -14,6 +14,8 @@ public class SignatureProfileSettings implements IProfileConstants { private Map<String, String> profileSettings = new HashMap<String, String>(); private String profileID; + + private ISettings configuration; public SignatureProfileSettings(String profileID, ISettings configuration) { this.profileID = profileID; @@ -21,6 +23,7 @@ public class SignatureProfileSettings implements IProfileConstants { String keysPrefix = profilePrefix + PROFILE_KEY; String valuesPrefix = profilePrefix + PROFILE_VALUE; String tablePrefix = profilePrefix + TABLE; + this.configuration = configuration; logger.debug("Reading Profile: " + profileID); logger.debug("Keys Prefix: " + keysPrefix); @@ -100,22 +103,39 @@ public class SignatureProfileSettings implements IProfileConstants { return null; } + protected String getDefaultValue(String key) { + String profilePrefix = SIG_OBJ + profileID + KEY_SEPARATOR; + logger.debug("Searching default value for: " + key); + if(key.startsWith(profilePrefix)) { + key = key.substring(profilePrefix.length()); + } + key = "default." + key; + logger.debug("Searching default value for: " + key); + return this.configuration.getValue(key); + } + public String getValue(String key) { + logger.debug("Searching: " + key); SignatureProfileEntry entry = profileInformations.get(key); if(entry != null) { String value = entry.getValue(); if(value == null) { // TODO: try to find default value for key! + return getDefaultValue(key); } return value; } // TODO: try to find default value for key! - return null; + return getDefaultValue(key); } public String getProfileID() { return profileID; } + + public String getSigningReason() { + return this.getValue(SIGNING_REASON); + } } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/IConfigurationConstants.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/IConfigurationConstants.java index 59515937..21f8c81e 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/IConfigurationConstants.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/IConfigurationConstants.java @@ -3,6 +3,7 @@ package at.gv.egiz.pdfas.lib.api; public interface IConfigurationConstants { public static final String TRUE = "true"; + public static final String FALSE = "false"; public static final String SIG_OBJECT = "sig_obj"; public static final String TYPE = "type"; @@ -11,6 +12,9 @@ public interface IConfigurationConstants { public static final String POS = "pos"; public static final String DEFAULT = "default"; public static final String SEPERATOR = "."; + + + public static final String LEGACY_POSITIONING = ".legacy.pos"; public static final String PLACEHOLDER_SEARCH_ENABLED = "enable_placeholder_search"; public static final String DEFAULT_SIGNATURE_PROFILE = SIG_OBJECT + SEPERATOR + TYPE + SEPERATOR + DEFAULT; diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/PdfAsFactory.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/PdfAsFactory.java index b303a139..963e4098 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/PdfAsFactory.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/api/PdfAsFactory.java @@ -1,12 +1,19 @@ package at.gv.egiz.pdfas.lib.api; -import iaik.security.ecc.provider.ECCProvider; +import iaik.security.ec.provider.ECCelerate; import iaik.security.provider.IAIK; +import java.io.BufferedOutputStream; import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; -import org.apache.log4j.BasicConfigurator; import org.apache.log4j.PropertyConfigurator; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import at.gv.egiz.pdfas.lib.api.sign.SignParameter; import at.gv.egiz.pdfas.lib.api.verify.VerifyParameter; @@ -15,26 +22,108 @@ import at.gv.egiz.pdfas.lib.impl.SignParameterImpl; import at.gv.egiz.pdfas.lib.impl.VerifyParameterImpl; public class PdfAsFactory { - + + private static final Logger logger = LoggerFactory + .getLogger(PdfAsFactory.class); + + private static final String DEFAULT_CONFIG_RES = "config/config.zip"; + static { - PropertyConfigurator.configure(ClassLoader.getSystemResourceAsStream("resources/log4j.properties")); - //BasicConfigurator.configure(); - - IAIK.getInstance(); - ECCProvider.addAsProvider(); + PropertyConfigurator.configure(ClassLoader + .getSystemResourceAsStream("resources/log4j.properties")); + // BasicConfigurator.configure(); + + //iaik.security.ecc.provider.ECCProvider.addAsProvider(); + IAIK.addAsProvider();; + //ECCProvider.addAsProvider(); + // install security provider + ECCelerate.addAsProvider(); } - + public static PdfAs createPdfAs(File configuration) { return new PdfAsImpl(configuration); } - - public static SignParameter createSignParameter(Configuration configuration, DataSource dataSource) { + + public static SignParameter createSignParameter( + Configuration configuration, DataSource dataSource) { SignParameter param = new SignParameterImpl(configuration, dataSource); return param; } - - public static VerifyParameter createVerifyParameter(Configuration configuration, DataSource dataSource) { - VerifyParameter param = new VerifyParameterImpl(configuration, dataSource); + + public static VerifyParameter createVerifyParameter( + Configuration configuration, DataSource dataSource) { + VerifyParameter param = new VerifyParameterImpl(configuration, + dataSource); return param; } + + public static void deployDefaultConfiguration(File targetDirectory) + throws Exception { + if (targetDirectory.exists()) { + targetDirectory.delete(); + } + + if (!targetDirectory.exists()) { + targetDirectory.mkdir(); + } + InputStream is = ClassLoader + .getSystemResourceAsStream(DEFAULT_CONFIG_RES); + // URL zipUrl = ClassLoader.getSystemResource(DEFAULT_CONFIG_RES); + // logger.debug("CONFIG URI: " + zipUrl.toURI().toString()); + // File zipFile = new File(zipUrl.toURI()); + // ZipFile zip = null; + ZipInputStream zip = null; + try { + zip = new ZipInputStream(is); + + ZipEntry entry = zip.getNextEntry(); + while (entry != null) { + + File destinationPath = new File( + targetDirectory.getAbsolutePath(), entry.getName()); + + // create parent directories + destinationPath.getParentFile().mkdirs(); + + // if the entry is a file extract it + if (entry.isDirectory()) { + destinationPath.mkdir(); + zip.closeEntry(); + entry = zip.getNextEntry(); + continue; + } else { + + logger.debug("Extracting file: " + destinationPath); + + int b; + byte buffer[] = new byte[1024]; + + FileOutputStream fos = new FileOutputStream(destinationPath); + + BufferedOutputStream bos = new BufferedOutputStream(fos, + 1024); + + while ((b = zip.read(buffer, 0, 1024)) != -1) { + bos.write(buffer, 0, b); + } + + bos.close(); + zip.closeEntry(); + + } + entry = zip.getNextEntry(); + } + + } catch (IOException ioe) { + System.out.println("Error opening zip file" + ioe); + } finally { + try { + if (zip != null) { + zip.close(); + } + } catch (IOException ioe) { + System.out.println("Error while closing zip file" + ioe); + } + } + } } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/PdfAsImpl.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/PdfAsImpl.java index ddfc79ce..fc245592 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/PdfAsImpl.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/PdfAsImpl.java @@ -459,7 +459,7 @@ public class PdfAsImpl implements PdfAs, IConfigurationConstants { PositioningInstruction positioningInstruction = Positioning .determineTablePositioning(tablePos, "", originalDocument, - visualObject); + visualObject, false); // ================================================================ // StampingStage (visual) -> stamp logical signature block to @@ -524,6 +524,8 @@ public class PdfAsImpl implements PdfAs, IConfigurationConstants { .getDefaultPositioning(); } + boolean legacy32Position = signatureProfileConfiguration.getLegacy32Positioning(); + TablePos tablePos = null; if (posString == null) { @@ -538,7 +540,7 @@ public class PdfAsImpl implements PdfAs, IConfigurationConstants { PositioningInstruction positioningInstruction = Positioning .determineTablePositioning(tablePos, "", originalDocument, - visualObject); + visualObject, legacy32Position); // ================================================================ // StampingStage (visual) -> stamp logical signature block to diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/configuration/SignatureProfileConfiguration.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/configuration/SignatureProfileConfiguration.java index 8f09b495..b8a0139a 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/configuration/SignatureProfileConfiguration.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/configuration/SignatureProfileConfiguration.java @@ -23,4 +23,15 @@ public class SignatureProfileConfiguration extends SpecificBaseConfiguration String key = SIG_OBJECT + SEPERATOR + profileID + SEPERATOR + TABLE + SEPERATOR + POS; return this.configuration.getValue(key); } + + public boolean getLegacy32Positioning() { + String key = SIG_OBJECT + SEPERATOR + profileID + LEGACY_POSITIONING; + String value = this.configuration.getValue(key); + if(value != null) { + if(value.equalsIgnoreCase(TRUE)) { + return true; + } + } + return false; + } } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/positioning/Positioning.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/positioning/Positioning.java index 340ba0bb..da7da772 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/positioning/Positioning.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/positioning/Positioning.java @@ -47,39 +47,8 @@ public class Positioning { * F.e. */ public static PositioningInstruction determineTablePositioning(TablePos pos, String signature_type, - PDDocument pdfDataSource, IPDFVisualObject pdf_table) throws PdfAsException + PDDocument pdfDataSource, IPDFVisualObject pdf_table, boolean legacy32) throws PdfAsException { - boolean legacy32 = false; - - //TODO: settings reader ... - - /* - if (pos == null) - { - String pos_string = SettingsReader.getInstance().getSetting(SignatureTypes.SIG_OBJ + signature_type + ".pos", null); - if (pos_string != null) - { - pos = PdfAS.parsePositionFromPosString(pos_string); - } - } - if (pos == null) - { - // The default algorithm. x,y,w =auto ,p=lastpage, f:ignored because - // y:auto - pos = new TablePos(); - } - - // afitzek - // Allow legacy positioning (3.2) for BRZ Templates ... - boolean legacy32 = false; - String leg = SettingsReader.getInstance().getSetting(SignatureTypes.SIG_OBJ + signature_type + ".legacy.pos", "false"); - if (leg != null) { - if ("true".equals(leg.trim())) { - legacy32 = true; - } - } - */ - // System.out.println("Tablepos="+pos); return adjustSignatureTableandCalculatePosition(pdfDataSource, pdf_table, pos, legacy32); } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PADESPDFBOXSigner.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PADESPDFBOXSigner.java index 7273b8a9..cc75ff69 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PADESPDFBOXSigner.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PADESPDFBOXSigner.java @@ -65,11 +65,16 @@ public class PADESPDFBOXSigner implements IPdfSigner { String signerName = resolver.resolve("SIG_SUBJECT", signatureProfileSettings.getValue("SIG_SUBJECT"), signatureProfileSettings, requestedSignature); - signature.setName(signerName); - //signature.setLocation("signer location"); - signature.setReason("PDF-AS Signatur"); - + signature.setSignDate(Calendar.getInstance()); + String signerReason = signatureProfileSettings.getSigningReason(); + + if(signerReason == null) { + signerReason = "PAdES Signature"; + } + + signature.setReason(signerReason); + logger.debug("Signing reason: " + signerReason); logger.debug("Signing @ " + signer.getSigningDate().getTime().toString()); // the signing date, needed for valid signature diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PdfboxSignerWrapper.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PdfboxSignerWrapper.java index 554a5b98..718acc24 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PdfboxSignerWrapper.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/lib/impl/signing/pdfbox/PdfboxSignerWrapper.java @@ -42,10 +42,10 @@ public class PdfboxSignerWrapper implements PDFASSignatureInterface { try { byte[] signature = signer.sign(data, byteRange); /*logger.debug("Signature Data: " - + iaik.utils.Util.toBase64String(signature)); + + iaik.utils.Util.toBase64String(signature));*/ FileOutputStream fos = new FileOutputStream("/tmp/fos.bin"); fos.write(signature); - fos.close();*/ + fos.close(); return signature; } catch (PdfAsException e) { throw new PdfAsWrappedIOException(e); diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/ISignatureConnectorSLWrapper.java b/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/ISignatureConnectorSLWrapper.java index cf7333b4..409b984f 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/ISignatureConnectorSLWrapper.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/ISignatureConnectorSLWrapper.java @@ -1,7 +1,12 @@ package at.gv.egiz.sl.util; +import iaik.cms.CMSException; +import iaik.cms.SignedData; +import iaik.cms.SignerInfo; +import iaik.x509.X509Certificate; + import java.io.ByteArrayInputStream; -import java.security.MessageDigest; +import java.io.IOException; import java.security.SignatureException; import java.security.cert.CertificateException; import java.util.Iterator; @@ -9,12 +14,8 @@ import java.util.Iterator; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import iaik.cms.SignedData; -import iaik.cms.SignerInfo; -import iaik.x509.X509Certificate; import at.gv.egiz.pdfas.common.exceptions.PdfAsException; -import at.gv.egiz.pdfas.common.utils.StringUtils; -import at.gv.egiz.pdfas.lib.api.sign.IPlainSigner; +import at.gv.egiz.pdfas.common.exceptions.PdfAsSignatureException; import at.gv.egiz.pdfas.lib.impl.verify.VerifyResultImpl; import at.gv.egiz.sl.CreateCMSSignatureRequestType; import at.gv.egiz.sl.CreateCMSSignatureResponseType; @@ -72,11 +73,16 @@ public class ISignatureConnectorSLWrapper implements ISignatureConnector { // get the signer infos SignerInfo[] signerInfos = signedData.getSignerInfos(); + if (signerInfos.length == 0) { + throw new PdfAsSignatureException("Invalid Signature (no signer info created!)", null); + } // verify the signatures for (int i = 0; i < signerInfos.length; i++) { VerifyResultImpl verifyResult = new VerifyResultImpl(); try { - + logger.info("Signature Algo: {}, Digest {}", signedData + .getSignerInfos()[i].getSignatureAlgorithm(), + signedData.getSignerInfos()[i].getDigestAlgorithm()); // verify the signature for SignerInfo at index i X509Certificate signer_cert = signedData.verify(i); // if the signature is OK the certificate of the @@ -84,21 +90,27 @@ public class ISignatureConnectorSLWrapper implements ISignatureConnector { logger.info("Signature OK from signer: " + signer_cert.getSubjectDN()); verifyResult.setSignerCertificate(signer_cert); + } catch (SignatureException ex) { // if the signature is not OK a SignatureException // is thrown - logger.info("Signature ERROR from signer: " - + signedData.getCertificate( - signerInfos[i].getSignerIdentifier()) - .getSubjectDN()); + logger.error( + "Signature ERROR from signer: " + + signedData.getCertificate( + signerInfos[i] + .getSignerIdentifier()) + .getSubjectDN(), ex); verifyResult.setSignerCertificate(signedData .getCertificate(signerInfos[i] .getSignerIdentifier())); + throw new PdfAsSignatureException("Invalid Signature", ex); } } - } catch (Exception e) { - logger.error("ERROR", e); + } catch (CMSException e) { + throw new PdfAsSignatureException("Invalid Signature", e); + } catch (IOException e) { + throw new PdfAsSignatureException("Invalid Signature", e); } return response.getCMSSignature(); diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/MOAConnector.java b/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/MOAConnector.java index d75aa66e..d46f34a3 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/MOAConnector.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/sl/util/MOAConnector.java @@ -2,41 +2,78 @@ package at.gv.egiz.sl.util; import iaik.x509.X509Certificate; +import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; +import java.io.InputStreamReader; import java.security.cert.CertificateException; import javax.activation.DataHandler; +import org.apache.axis2.databinding.types.Token; +import org.apache.commons.codec.binary.Base64; +import org.apache.http.HttpResponse; +import org.apache.http.client.entity.EntityBuilder; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.mime.MultipartEntityBuilder; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import at.gv.egiz.moa.ByteArrayDataSource; import at.gv.egiz.moa.SignatureCreationServiceStub; import at.gv.egiz.moa.SignatureCreationServiceStub.CMSContentBaseType; import at.gv.egiz.moa.SignatureCreationServiceStub.CreateCMSSignatureRequest; import at.gv.egiz.moa.SignatureCreationServiceStub.CreateCMSSignatureResponse; +import at.gv.egiz.moa.SignatureCreationServiceStub.CreateSignatureInfo_type0; import at.gv.egiz.moa.SignatureCreationServiceStub.DataObjectInfo_type1; import at.gv.egiz.moa.SignatureCreationServiceStub.DataObject_type1; import at.gv.egiz.moa.SignatureCreationServiceStub.KeyIdentifierType; +import at.gv.egiz.moa.SignatureCreationServiceStub.MetaInfoType; +import at.gv.egiz.moa.SignatureCreationServiceStub.MimeTypeType; import at.gv.egiz.moa.SignatureCreationServiceStub.SingleSignatureInfo_type1; +import at.gv.egiz.moa.SignatureCreationServiceStub.Structure_type1; import at.gv.egiz.pdfas.common.exceptions.PdfAsException; import at.gv.egiz.pdfas.common.utils.StreamUtils; import at.gv.egiz.pdfas.lib.api.Configuration; public class MOAConnector implements ISignatureConnector { + private static final Logger logger = LoggerFactory + .getLogger(MOAConnector.class); + public static final String MOA_SIGN_URL = "moa.sign.url"; public static final String MOA_SIGN_KEY_ID = "moa.sign.KeyIdentifier"; public static final String MOA_SIGN_CERTIFICATE = "moa.sign.Certificate"; - + + public static final String KEY_ID_PATTERN = "##KEYID##"; + public static final String CONTENT_PATTERN = "##CONTENT##"; + + public static final String CMS_REQUEST = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ns=\"http://reference.e-government.gv.at/namespace/moa/20020822#\">" + + "<soapenv:Header/><soapenv:Body><ns:CreateCMSSignatureRequest><ns:KeyIdentifier>" + + KEY_ID_PATTERN + + "</ns:KeyIdentifier>" + + "<ns:SingleSignatureInfo SecurityLayerConformity=\"true\"><ns:DataObjectInfo Structure=\"detached\"><ns:DataObject>" + + "<ns:MetaInfo><ns:MimeType>application/pdf</ns:MimeType></ns:MetaInfo><ns:Content>" + + "<ns:Base64Content>" + + CONTENT_PATTERN + + "</ns:Base64Content>" + + "</ns:Content></ns:DataObject></ns:DataObjectInfo></ns:SingleSignatureInfo>" + + "</ns:CreateCMSSignatureRequest></soapenv:Body></soapenv:Envelope>"; + private X509Certificate certificate; private String moaEndpoint; private String keyIdentifier; - public MOAConnector(Configuration config) - throws CertificateException, FileNotFoundException, IOException { - this.certificate = new X509Certificate(new FileInputStream(new File(config.getValue(MOA_SIGN_CERTIFICATE)))); + public MOAConnector(Configuration config) throws CertificateException, + FileNotFoundException, IOException { + this.certificate = new X509Certificate(new FileInputStream(new File( + config.getValue(MOA_SIGN_CERTIFICATE)))); this.moaEndpoint = config.getValue(MOA_SIGN_URL); this.keyIdentifier = config.getValue(MOA_SIGN_KEY_ID); } @@ -45,40 +82,114 @@ public class MOAConnector implements ISignatureConnector { return this.certificate; } + private CloseableHttpClient buildHttpClient() { + HttpClientBuilder builder = HttpClientBuilder.create(); + return builder.build(); + } + public byte[] sign(byte[] input, int[] byteRange) throws PdfAsException { + CloseableHttpClient client = null; try { - SignatureCreationServiceStub signatureCreationService = new SignatureCreationServiceStub( - this.moaEndpoint); - - CreateCMSSignatureRequest createCMSSignatureRequest = new CreateCMSSignatureRequest(); - SingleSignatureInfo_type1 singleSignature = new SingleSignatureInfo_type1(); - DataObjectInfo_type1 dataObjectType = new DataObjectInfo_type1(); - singleSignature.setDataObjectInfo(dataObjectType); - DataObject_type1 dataObject = new DataObject_type1(); - dataObjectType.setDataObject(dataObject); - CMSContentBaseType cmsContent = new CMSContentBaseType(); - cmsContent.setBase64Content(new DataHandler( - new ByteArrayDataSource(input, "application/pdf"))); - dataObject.setContent(cmsContent); - - createCMSSignatureRequest - .setSingleSignatureInfo(new SingleSignatureInfo_type1[] { singleSignature }); - KeyIdentifierType keyId = new KeyIdentifierType(); - keyId.setKeyIdentifierType(this.keyIdentifier); - createCMSSignatureRequest.setKeyIdentifier(keyId); - - CreateCMSSignatureResponse response = signatureCreationService - .createCMSSignature(createCMSSignatureRequest); - - InputStream is = response.getCreateCMSSignatureResponse() - .getCreateCMSSignatureResponseTypeChoice()[0] - .getCMSSignature().getInputStream(); + client = buildHttpClient(); + HttpPost post = new HttpPost(this.moaEndpoint); + + logger.info("signature with MOA [" + this.keyIdentifier + "] @ " + + this.moaEndpoint); + + Base64 base64 = new Base64(); + String content = base64.encodeAsString(input); + + String request = CMS_REQUEST; + request = request.replace(CONTENT_PATTERN, content.trim()); + request = request + .replace(KEY_ID_PATTERN, this.keyIdentifier.trim()); + + //SOAPAction: "urn:CreateCMSSignatureAction" + post.setHeader("SOAPAction", "urn:CreateCMSSignatureAction"); - byte[] signature = StreamUtils.inputStreamToByteArray(is); + EntityBuilder entityBuilder = EntityBuilder.create(); - return signature; - } catch (Exception e) { - throw new PdfAsException(e.getMessage()); + entityBuilder.setContentType(ContentType.TEXT_XML); + entityBuilder.setContentEncoding("UTF-8"); + entityBuilder.setText(request); + + post.setEntity(entityBuilder.build()); + + HttpResponse response = client.execute(post); + logger.debug("Response Code : " + + response.getStatusLine().getStatusCode()); + + BufferedReader rd = new BufferedReader(new InputStreamReader( + response.getEntity().getContent())); + + StringBuffer result = new StringBuffer(); + String line = ""; + while ((line = rd.readLine()) != null) { + result.append(line); + } + + logger.trace(result.toString()); + return new byte[] {}; + } catch (IllegalStateException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } finally { + if (client != null) { + try { + client.close(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + } } + return new byte[] {}; } + + /* + * public byte[] sign(byte[] input, int[] byteRange) throws PdfAsException { + * try { + * + * SignatureCreationServiceStub signatureCreationService = new + * SignatureCreationServiceStub( this.moaEndpoint); + * + * CreateCMSSignatureRequest createCMSSignatureRequest = new + * CreateCMSSignatureRequest(); KeyIdentifierType keyId = new + * KeyIdentifierType(); keyId.setKeyIdentifierType(keyIdentifier); + * createCMSSignatureRequest.setKeyIdentifier(keyId); + * + * SingleSignatureInfo_type1 singleSignature = new + * SingleSignatureInfo_type1(); DataObjectInfo_type1 dataObjectType = new + * DataObjectInfo_type1(); + * + * dataObjectType.setStructure(Structure_type1.detached); + * singleSignature.setDataObjectInfo(dataObjectType); DataObject_type1 + * dataObject = new DataObject_type1(); MetaInfoType metaInfoType = new + * MetaInfoType(); MimeTypeType mimeTypeType = new MimeTypeType(); + * mimeTypeType.setMimeTypeType(new Token("application/pdf")); + * metaInfoType.setMimeType(mimeTypeType); + * dataObject.setMetaInfo(metaInfoType); + * dataObjectType.setDataObject(dataObject); CMSContentBaseType cmsContent = + * new CMSContentBaseType(); cmsContent.setBase64Content(new DataHandler( + * new ByteArrayDataSource(input, "application/pdf"))); + * + * dataObject.setContent(cmsContent); + * + * createCMSSignatureRequest.addSingleSignatureInfo(singleSignature); + * + * CreateCMSSignatureResponse response = signatureCreationService + * .createCMSSignature(createCMSSignatureRequest); + * + * InputStream is = response.getCreateCMSSignatureResponse() + * .getCreateCMSSignatureResponseTypeChoice()[0] + * .getCMSSignature().getInputStream(); + * + * byte[] signature = StreamUtils.inputStreamToByteArray(is); + * + * return signature; } catch (Exception e) { throw new + * PdfAsException(e.getMessage()); } } + */ } |