From db52e4d66d60184d53a27ba4d6772461daacc03d Mon Sep 17 00:00:00 2001
From: tknall
* The document text is signed, but instead of returning the pdf with the signature block,
* the sign result XML of the connector is returned.
@@ -98,14 +98,14 @@ public final class Constants
* This value should not be modified due to external dependencies!
*/
public static final String SIGNATURE_DEVICE_MOBILE = "mobile";
-
+
/**
* Added by rpiazzi
* The signature device MOBILETEST for the test version of the MOBILE CCS.
* This value should not be modified due to external dependencies!
*/
public static final String SIGNATURE_DEVICE_MOBILETEST = "mobiletest";
-
+
/**
* Only binary signatures are verified.
*/
@@ -113,7 +113,7 @@ public final class Constants
/**
* Binary and textual signatures are verified with time optimization.
- *
+ *
*
* This mode of operation tries to minimize the numbers of text extractions,
* which are very time intensive, at the cost of some rare cases, in which some
@@ -141,19 +141,19 @@ public final class Constants
* The zip file containing the default configuration.
*/
public static final String DEFAULT_CONFIGURATION_ZIP_RESOURCE = "DefaultConfiguration.zip";
-
+
/**
* The configuration folder for pdf-as within the user's home folder.
*/
public static final String USERHOME_CONFIG_FOLDER = "PDF-AS";
-
+
/**
* The name of the directory, where temporary files are stored.
*/
public static final String TEMP_DIR_NAME = "pdfastmp";
-
+
public static final String BKU_HEADER_SIGNATURE_LAYOUT = "SignatureLayout";
-
+
public static final String ADOBE_SIG_FILTER = AdobeSignatureHelper.ADOBE_SIG_FILTER;
/**
@@ -161,25 +161,30 @@ public final class Constants
* If the placeholder with the given id is not found in the document, an exception will be thrown.
*/
public static final int PLACEHOLDER_MATCH_MODE_STRICT = 0;
-
+
/**
* A moderate matching mode for placeholder extraction.
* The DataSource implementation encapsulates the actual representaion of the
* data. E.g. the DataSource may be File based or byte array based. See
@@ -54,7 +54,7 @@ public class SignParameters
/**
* The type of the signature.
- *
+ *
*
* May be {@link Constants#SIGNATURE_TYPE_BINARY} or
* {@link Constants#SIGNATURE_TYPE_TEXTUAL}.
@@ -64,7 +64,7 @@ public class SignParameters
/**
* The signature device to perform the actual signature.
- *
+ *
*
* May be {@link Constants#SIGNATURE_DEVICE_MOA} or
* {@link Constants#SIGNATURE_DEVICE_BKU}.
@@ -75,18 +75,18 @@ public class SignParameters
/**
* The signature profile identifier identifying the profile to be used in the
* config file.
- *
+ *
*
* Note: In near future it will be possible to provide a full specified
* profile here instead of the profile id.
*
* Providing a null value (default) means that no explicit signature key
* identifier is provided. The selected signature device will then use its
@@ -122,7 +122,7 @@ public class SignParameters
* The output DataSink that will receive the signed document.
*/
protected DataSink output = null;
-
+
protected TimeStamper timeStamperImpl;
/**
@@ -142,12 +142,12 @@ public class SignParameters
* Defaults to {@link Constants#PLACEHOLDER_MATCH_MODE_MODERATE}.
*/
protected int placeholderMatchMode = Constants.PLACEHOLDER_MATCH_MODE_MODERATE;
-
+
protected Properties overrideProps = new Properties();
-
-
+
+
/**
* {@link #setTimeStamperImpl(TimeStamper)}
@@ -158,7 +158,7 @@ public class SignParameters
}
/**
- * Set a {@link TimeStamper} to create a timestamp on the signature value. Will be
+ * Set a {@link TimeStamper} to create a timestamp on the signature value. Will be
* called after sign. For binary signatures only. Timestamp will be embedded in egiz dict /TimeStamp.
* @param timeStamperImpl
*/
@@ -285,21 +285,21 @@ public class SignParameters
}
/**
- * Override user defined values from the used signature profile like "value.SIG_META".
- * You cannot override pre defined values like SIG_VALUE, SIG_DATE {@link SignatureTypes#REQUIRED_SIG_KEYS}.
+ * Override user defined values from the used signature profile like "value.SIG_META".
+ * You cannot override pre defined values like SIG_VALUE, SIG_DATE {@link SignatureTypes#REQUIRED_SIG_KEYS}.
* The override values are bound to the {@link SignParameters} instance.
*
* Sample usage:
*
* The commandline uses the PDF-AS API.
*
* The extension of a file name is whatever text follows the last '.'.
*
* In prepareSign, an Incremental Update is created that contains the Signature block and the egiz dictionary. For
* formatting the layout, variable values are filled with placeholders. After the layout has been fixed, all variable
@@ -92,7 +92,7 @@ import com.lowagie.text.pdf.PdfPTable;
*
* In finishSign, the variable fields (values, /Cert) are replaced with the values according to the encoding.
*
* In prepareSign, the document text is extracted and normalized.
*
* If the placeholder with the given id is not found in the document, the first placeholder without an id will be taken.
* If there is no such placeholder, the signature will be placed as usual, according to the pos parameter of the signature profile used.
*/
public static final int PLACEHOLDER_MATCH_MODE_MODERATE = 1;
-
+
/**
* A more lenient matching mode for placeholder extraction.
* If the placeholder with the given id is not found in the document, the first found placeholder will be taken, regardless if it has an id set, or not.
* If there is no placeholder at all, the signature will be placed as usual, according to the pos parameter of the signature profile used.
*/
public static final int PLACEHOLDER_MATCH_MODE_LENIENT = 2;
-
+
/**
* Identifier for QR based placeholders.
*/
public static final String QR_PLACEHOLDER_IDENTIFIER = "PDF-AS-POS";
-
+
+ /**
+ * The name of a logger used for statistical logging.
+ */
+ public static final String STATISTIC_LOGGER_NAME = "statistic";
+
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/DynamicSignatureProfileImpl.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/DynamicSignatureProfileImpl.java
index 7e1672a..e1f31f7 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/DynamicSignatureProfileImpl.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/DynamicSignatureProfileImpl.java
@@ -159,8 +159,10 @@ public class DynamicSignatureProfileImpl implements DynamicSignatureProfile {
cfg = SettingsReader.getInstance();
- Properties props = cfg.getProperties();
- for (Enumeration e = props.keys(); e.hasMoreElements();) {
+ Properties props = cfg.getProperties();
+ // DTI: props.keys() does not support default properties, therefore we should better use props.propertyNames()
+// for (Enumeration e = props.keys(); e.hasMoreElements();) {
+ for (Enumeration e = props.propertyNames(); e.hasMoreElements();) {
String oldKey = (String) e.nextElement();
if (oldKey.startsWith("sig_obj." + parentProfile + ".")) {
String newKey = StringUtils.replace(oldKey, parentProfile, name);
@@ -168,7 +170,7 @@ public class DynamicSignatureProfileImpl implements DynamicSignatureProfile {
this.newProps.put(newKey, val);
}
}
- this.newProps.put("sig_obj.types." + name, "on");
+ this.newProps.put("sig_obj.types." + name, "on");
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/SignatureProfile.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/SignatureProfile.java
index 8cd3108..1325d04 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/SignatureProfile.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/commons/SignatureProfile.java
@@ -25,6 +25,8 @@ package at.gv.egiz.pdfas.api.commons;
import java.util.Properties;
+import at.knowcenter.wag.egov.egiz.sig.SignatureTypes.State;
+
/**
* Definition of a signature profile.
*
@@ -73,4 +75,13 @@ public interface SignatureProfile {
* @return
*/
public boolean isDefault();
+
+ /**
+ * Returns the state of the signature profile. Signature profiles may be restricted to signature (
+ * {@link State#SIGN_ONLY}) or to verification ({@link State#VERIFY_ONLY}).
+ *
+ * @return The state of the profile.
+ */
+ public State getState();
+
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/sign/SignParameters.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/sign/SignParameters.java
index 8834481..5533b8b 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/sign/SignParameters.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/api/sign/SignParameters.java
@@ -34,16 +34,16 @@ import at.knowcenter.wag.egov.egiz.sig.SignatureTypes;
/**
* Parameter object that holds the sign parameters.
- *
+ *
* @author wprinz
*/
public class SignParameters
{
// 23.11.2010 changed by exthex - added parameters for placeholder handling
-
+
/**
* The document to be signed.
- *
+ *
*
SignParameters sp = new SignParameters();
. . .
-
- sp.setSignatureProfileId("SIGNATURBLOCK_DE");
-
+
+ sp.setSignatureProfileId("SIGNATURBLOCK_DE");
+
// expressions do not work on binary signature fields without phlength setting!!
sp.setProfileOverrideValue("SIG_META", "It's nice to be important, but it is more important to be nice ${subject.L}");;
- sp.setProfileOverrideValue("SIG_LABEL", "./images/signatur-logo_en.png");
-
+ sp.setProfileOverrideValue("SIG_LABEL", "./images/signatur-logo_en.png");
+
// execute sign using the overrides
pdfAs.sign(sp);
@@ -311,51 +311,51 @@ public class SignParameters
if (SignatureTypes.isRequredSigTypeKey(key)) {
throw new RuntimeException("cannot set value for pre defined signature field names");
}
- this.overrideProps.put(key, value);
+ this.overrideProps.put(key, value);
}
-
+
/**
* Get override values created via {@link #setProfileOverrideValue(String, String)}
* @return
*/
public Properties getProfileOverrideProperties() {
return this.overrideProps;
-
+
}
/**
* Get the value of the checkForPlaceholder flag.
- *
+ *
* @return
*/
public Boolean isCheckForPlaceholder() {
return this.checkForPlaceholder;
}
-
+
/**
- * Set this to true, if you want a search for placeholder images to be performed and
+ * Set this to true, if you want a search for placeholder images to be performed and
* appropriate images to be replaced.
* If this is not set, a search will only be performed if the configuration property "enable_placeholder_search" is set to true.
- *
+ *
* @param check
*/
- public void setCheckForPlaceholder(boolean check) {
- this.checkForPlaceholder = Boolean.valueOf(check);
+ public void setCheckForPlaceholder(Boolean searchForPlaceHolder) {
+ this.checkForPlaceholder = searchForPlaceHolder;
}
/**
- * Set an explicit placeholder id.
+ * Set an explicit placeholder id.
* Only placeholder images that have a matching ID property embedded will be considered for replacement.
- *
+ *
* @param placeholderId
*/
public void setPlaceholderId(String placeholderId) {
- this.placeholderId = placeholderId;
+ this.placeholderId = placeholderId;
}
-
+
/**
* The id of the placeholder to replace.
- *
+ *
* @return the placeholderId
*/
public String getPlaceholderId() {
@@ -367,13 +367,13 @@ public class SignParameters
* Exactly matching meaning:
*
- *
+ *
* @see Constants#PLACEHOLDER_MATCH_MODE_LENIENT
* @see Constants#PLACEHOLDER_MATCH_MODE_MODERATE
* @see Constants#PLACEHOLDER_MATCH_MODE_STRICT
- *
+ *
* Defaults to {@link Constants#PLACEHOLDER_MATCH_MODE_MODERATE}.
- *
+ *
* @param placeholderMatchMode
*/
public void setPlaceholderMatchMode(int placeholderMatchMode) {
@@ -382,12 +382,12 @@ public class SignParameters
/**
* Get the placeholder matching mode.
- *
+ *
* @see SignParameters#getPlaceholderMatchMode()
* @return the placeholderMatchMode
*/
public int getPlaceholderMatchMode() {
return this.placeholderMatchMode;
}
-
+
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/commandline/Main.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/commandline/Main.java
index 52355f8..d5f7e2f 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/commandline/Main.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/commandline/Main.java
@@ -36,6 +36,7 @@ import java.util.Iterator;
import java.util.List;
import java.util.Set;
+import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
@@ -78,11 +79,11 @@ import at.knowcenter.wag.egov.egiz.sig.SignatureTypes;
/**
* The main program entry point of the commandline tool.
- *
+ *
*
+ * Note that it exclusively creates {@link CsvStatisticLogger} implementations at the moment. It should just be regarded
+ * as template for further factory implementations. Strictly speaking this factory does not fulfil the respective GoF
+ * pattern.
+ *
+ * @see StatisticLogger
+ * @author Datentechnik Innovation GmbH
+ */
+public class StatisticLogFactory {
+
+ /**
+ * Returns a statistic logger implementation.
+ *
+ * @param clazz
+ * The class.
+ * @return A statistic logger implementation.
+ */
+ public static StatisticLogger getLog(Class> clazz) {
+ return getLog(clazz.getName());
+ }
+
+ /**
+ * Returns a statistic logger implementation.
+ *
+ * @param name
+ * The name of the logger.
+ * @return A statistic logger implementation.
+ */
+ public static StatisticLogger getLog(String name) {
+
+ // to be changed some day, producing various logger implementations
+ return new CsvStatisticLogger(LogFactory.getLog(name));
+ }
+
+}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/framework/logging/StatisticLogger.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/framework/logging/StatisticLogger.java
new file mode 100644
index 0000000..6e2c587
--- /dev/null
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/framework/logging/StatisticLogger.java
@@ -0,0 +1,47 @@
+/**
+ * true
: automatically registers IAIK JCE and ECC Provider;
* false
: providers will NOT be automatically registered, providers
- * needed have to be registered by the API user
+ * needed have to be registered by the API user
* @throws PdfAsException
* Thrown, if the configuration cannot be processed.
*/
@@ -174,12 +181,12 @@ public class PdfAsObject implements PdfAs
SettingsReader.initialize(path, path);
reloadConfig(registerProvider);
}
-
+
/**
* This constructor is for internal use only - use
* {@link at.gv.egiz.pdfas.PdfAsFactory} instead.
* Note: IAIK JCE and IAIK ECC security providers are automatically registered.
- *
+ *
* @throws PdfAsException
* Thrown, if the configuration cannot be processed.
*/
@@ -187,7 +194,7 @@ public class PdfAsObject implements PdfAs
{
this(null);
}
-
+
/**
* @see at.gv.egiz.pdfas.api.PdfAs#reloadConfig()
*/
@@ -197,11 +204,11 @@ public class PdfAsObject implements PdfAs
SettingsReader.createInstance();
SignatureTypes.createInstance();
}
-
+
/**
* @param registerProvider true
: automatically registers IAIK JCE and ECC Provider;
* false
: providers will NOT be automatically registered, providers
- * needed have to be registered by the API user
+ * needed have to be registered by the API user
* @see at.gv.egiz.pdfas.api.PdfAs#reloadConfig()
*/
private void reloadConfig(boolean registerProvider) throws PdfAsException
@@ -228,7 +235,7 @@ public class PdfAsObject implements PdfAs
List profileInformation = new ArrayList(profiles.size());
String default_type = settings.getValueFromKey(SignatureTypes.DEFAULT_TYPE);
-
+
Iterator it = profiles.iterator();
while (it.hasNext())
{
@@ -240,14 +247,17 @@ public class PdfAsObject implements PdfAs
final String profileDescription = settings.getSetting("sig_obj." + profileId + "." + SignatureTypes.SIG_DESCR, null);
boolean isDefault = (default_type != null && default_type.equals(profileId));
+
+ State state = State.fromString(settings.getSetting(SignatureTypes.TYPES + "." + profileId));
+
// modified by tknall
- SignatureProfileImpl signatureProfile = new SignatureProfileImpl(profileId, profileDescription, moaKeyIdentifier, isDefault);
+ SignatureProfileImpl signatureProfile = new SignatureProfileImpl(profileId, state, profileDescription, moaKeyIdentifier, isDefault);
// start - added by tknall
-
+
// signature entries relevant to the search algorithm
Properties signatureEntries = new Properties();
-
+
// search for table entries
String parentPropertyKey = "sig_obj." + profileId + ".table";
log.debug("Looking for subkeys of \"" + parentPropertyKey + "\".");
@@ -275,7 +285,7 @@ public class PdfAsObject implements PdfAs
}
}
}
-
+
// search for table entries
parentPropertyKey = "sig_obj." + profileId + ".key";
log.debug("Looking for subkeys of \"" + parentPropertyKey + "\".");
@@ -295,46 +305,89 @@ public class PdfAsObject implements PdfAs
}
}
}
-
+
// set properties
signatureProfile.setSignatureBlockEntries(signatureEntries);
// stop - added by tknall
-
+
profileInformation.add(signatureProfile);
}
return profileInformation;
}
- /**
- * @see at.gv.egiz.pdfas.api.PdfAs#sign(at.gv.egiz.pdfas.api.sign.SignParameters)
- */
- public SignResult sign(SignParameters signParameters) throws PdfAsException
+ public SignResult sign(SignParameters signParameters) throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(signParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performSign(signParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ statLog.log(sd);
+ }
+ }
+
+ private SignResult performSign(SignParameters signParameters) throws PdfAsException
{
CheckHelper.checkSignParameters(signParameters, false);
-
+
+ // make sure that the selected profile is allowed to be used for signature
+ SettingsReader settings = SettingsReader.getInstance();
+ if (!State.fromString(settings.getSetting(SignatureTypes.TYPES + "." + signParameters.getSignatureProfileId()))
+ .canSign()) {
+ throw new SignatureException(ErrorCode.SIGNATURE_PROFILE_IS_NOT_ALLOWED_FOR_SIGNATURE,
+ "The signature profile '" + signParameters.getSignatureProfileId()
+ + "' is not allowed to be used for signature.");
+ }
+
try {
- SignatureDetailInformation signatorInfo = prepareSign(signParameters);
-
- return sign(signParameters, signatorInfo);
-
+
+ SignatureDetailInformation signatorInfo = performPrepareSign(signParameters);
+ return performSign(signParameters, signatorInfo);
+
} catch (java.lang.OutOfMemoryError e) {
throw new OutOfMemoryException(ErrorCode.OUT_OF_MEMORY_ERROR, "Insufficient memory allocated to virtual machine. Start Java with parameters \"-Xms128m -Xmx786m -XX:MaxPermSize=256m\".", e);
}
}
- /**
- * @see at.gv.egiz.pdfas.api.PdfAs#verify(at.gv.egiz.pdfas.api.verify.VerifyParameters)
- */
- public VerifyResults verify(VerifyParameters verifyParameters) throws PdfAsException
+ public VerifyResults verify(VerifyParameters verifyParameters) throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(verifyParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performVerify(verifyParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ statLog.log(sd);
+ }
+ }
+
+ private VerifyResults performVerify(VerifyParameters verifyParameters) throws PdfAsException
{
CheckHelper.checkVerifyParameters(verifyParameters);
AnalyzeParameters ap = new AnalyzeParameters();
fillAnalyzeParametersWithVerifyParameters(ap, verifyParameters);
- AnalyzeResult analyzeResult = analyze(ap);
+ AnalyzeResult analyzeResult = performAnalyze(ap);
if (verifyParameters.getSignatureToVerify() != Constants.VERIFY_ALL)
{
@@ -352,17 +405,17 @@ public class PdfAsObject implements PdfAs
VerifyAfterAnalysisParameters vaap = new VerifyAfterAnalysisParameters();
vaap.setAnalyzeResult(analyzeResult);
fillVerifyAfterAnalysisParametersWithVerifyParameters(vaap, verifyParameters);
- VerifyResults res = verify(vaap);
-
+ VerifyResults res = performVerify(vaap);
+
return res;
-
+
}
-
+
/**
* Copies all adequate parameters from the {@link VerifyParameters} to the
* {@link AnalyzeParameters}.
- *
+ *
* @param ap
* The {@link AnalyzeParameters}.
* @param vp
@@ -385,7 +438,7 @@ public class PdfAsObject implements PdfAs
/**
* Copies all adequate parameters from the {@link VerifyParameters} to the
* {@link VerifyAfterAnalysisParameters}.
- *
+ *
* @param vaap
* The {@link VerifyAfterAnalysisParameters}.
* @param vp
@@ -406,10 +459,30 @@ public class PdfAsObject implements PdfAs
reconstructParams.setSignatureDevice(verifyAfterAnalysisParameters.getSignatureDevice());
}
- /**
- * @see at.gv.egiz.pdfas.api.PdfAs#analyze(at.gv.egiz.pdfas.api.analyze.AnalyzeParameters)
- */
- public AnalyzeResult analyze(AnalyzeParameters analyzeParameters) throws PdfAsException
+ public AnalyzeResult analyze(AnalyzeParameters analyzeParameters) throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(analyzeParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performAnalyze(analyzeParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ // only log in case of error
+ if (sd.isError()) {
+ statLog.log(sd);
+ }
+ }
+ }
+
+ private AnalyzeResult performAnalyze(AnalyzeParameters analyzeParameters) throws PdfAsException
{
CheckHelper.checkAnalyzeParameters(analyzeParameters);
@@ -429,10 +502,12 @@ public class PdfAsObject implements PdfAs
assumeOnlySB = false;
}
VerificationFilterParameters parameters = new VerificationFilterParametersImpl(binaryOnly, assumeOnlySB, parametersConfig.scanForOldSignatures());
-
+
at.gv.egiz.pdfas.framework.input.DataSource inputDataSource = null;
if (analyzeParameters.getDocument().getMimeType().equals("application/pdf"))
{
+ // check document permissions
+ PDFASUtils.createPdfReaderCheckingPermissions(analyzeParameters.getDocument());
inputDataSource = new PdfDataSourceAdapter(analyzeParameters.getDocument());
}
else
@@ -447,13 +522,13 @@ public class PdfAsObject implements PdfAs
}
}
assert inputDataSource != null;
-
+
try {
ExtractionStage es = new ExtractionStage();
DataSourceHolder dsh = new DataSourceHolder(inputDataSource);
List signature_holders = es.extractSignatureHolders(dsh, parameters);
-
-
+
+
// List sigInfs = new ArrayList(signature_holders.size());
List sigInfs = new ArrayList();
List noSigs = new ArrayList();
@@ -461,24 +536,24 @@ public class PdfAsObject implements PdfAs
while (it.hasNext())
{
SignatureHolder sh = (SignatureHolder)it.next();
-
+
if(sh instanceof NoSignatureHolder) {
noSigs.add(sh);
} else {
-
+
SignatureInformation si = new SignatureInformationAdapter(sh);
sigInfs.add(si);
- if (analyzeParameters.isReturnNonTextualObjects()) {
- si.setNonTextualObjects(doExtractNonTexualObjects(sh, (PdfDataSource) dsh.getDataSource()));
- }
-
+ if (analyzeParameters.isReturnNonTextualObjects()) {
+ si.setNonTextualObjects(doExtractNonTexualObjects(sh, (PdfDataSource) dsh.getDataSource()));
+ }
+
}
}
return new AnalyzeResultImpl(sigInfs, noSigs, parameters.hasBeenCorrected());
} catch (java.lang.OutOfMemoryError e) {
throw new OutOfMemoryException(ErrorCode.OUT_OF_MEMORY_ERROR, "Insufficient memory allocated to virtual machine. Start Java with parameters \"-Xms128m -Xmx786m -XX:MaxPermSize=256m\".", e);
}
-
+
}
private List doExtractNonTexualObjects(SignatureHolder sh, PdfDataSource pdfDataSource) {
@@ -499,30 +574,47 @@ public class PdfAsObject implements PdfAs
}
}
-/**
- * @see at.gv.egiz.pdfas.api.PdfAs#verify(at.gv.egiz.pdfas.api.verify.VerifyAfterAnalysisParameters)
- */
- public VerifyResults verify(VerifyAfterAnalysisParameters verifyAfterAnalysisParameters) throws PdfAsException
+ public VerifyResults verify(VerifyAfterAnalysisParameters verifyAfterAnalysisParameters) throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(verifyAfterAnalysisParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performVerify(verifyAfterAnalysisParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ statLog.log(sd);
+ }
+ }
+
+ private VerifyResults performVerify(VerifyAfterAnalysisParameters verifyAfterAnalysisParameters) throws PdfAsException
{
CheckHelper.checkVerifyAfterAnalysisParameters(verifyAfterAnalysisParameters);
List signatures = verifyAfterAnalysisParameters.getAnalyzeResult().getSignatures();
-
+
// added by tknall
if (signatures == null || signatures.isEmpty()) {
throw new PDFDocumentException(ErrorCode.DOCUMENT_NOT_SIGNED, "PDF document not signed."); //$NON-NLS-1$
}
-
+
ReconstructXMLDsigAfterAnalysisParameters rxaap = new ReconstructXMLDsigAfterAnalysisParameters();
fillReconstructXMLDsigAfterAnalysisParametersWithVerifyAfterAnalysisParameters(rxaap, verifyAfterAnalysisParameters);
- ReconstructXMLDsigResult reconstructResult = reconstructXMLDSIG(rxaap);
-
+ ReconstructXMLDsigResult reconstructResult = performReconstructXMLDSIG(rxaap);
+
VerifyAfterReconstructXMLDsigParameters varxp = new VerifyAfterReconstructXMLDsigParameters();
fillVerifyAfterReconstructXMLDsigParametersWithVerifyAfterAnalysisParameters(varxp, verifyAfterAnalysisParameters);
varxp.setReconstructXMLDsigResult(reconstructResult);
-
- return verify(varxp);
-
+
+ return performVerify(varxp);
+
}
protected void fillVerifyAfterReconstructXMLDsigParametersWithVerifyAfterAnalysisParameters(
@@ -534,31 +626,75 @@ public class PdfAsObject implements PdfAs
varxp.setVerifySignatureIndex(verifyAfterAnalysisParameters.getVerifySignatureIndex());
}
- /**
- * @see PdfAs#reconstructXMLDSIG(ReconstructXMLDsigParameters)
- */
public ReconstructXMLDsigResult reconstructXMLDSIG(
+ ReconstructXMLDsigParameters reconstructXMLDsigParameters)
+ throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(reconstructXMLDsigParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performReconstructXMLDSIG(reconstructXMLDsigParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ // only log in case of error
+ if (sd.isError()) {
+ statLog.log(sd);
+ }
+ }
+ }
+
+ private ReconstructXMLDsigResult performReconstructXMLDSIG(
ReconstructXMLDsigParameters reconstructXMLDsigParameters)
throws PdfAsException {
-
+
AnalyzeParameters analyzeParameters = new AnalyzeParameters();
fillAnalyzeParametersWithReconstructXMLDsigParameters(analyzeParameters, reconstructXMLDsigParameters);
- AnalyzeResult ar = analyze(analyzeParameters);
-
+ AnalyzeResult ar = performAnalyze(analyzeParameters);
+
ReconstructXMLDsigAfterAnalysisParameters rxaap = new ReconstructXMLDsigAfterAnalysisParameters();
rxaap.setSignatureDevice(reconstructXMLDsigParameters.getSignatureDevice());
rxaap.setAnalyzeResult(ar);
-
- return reconstructXMLDSIG(rxaap);
+
+ return performReconstructXMLDSIG(rxaap);
}
- /**
- * @see PdfAs#reconstructXMLDSIG(ReconstructXMLDsigAfterAnalysisParameters)
- */
public ReconstructXMLDsigResult reconstructXMLDSIG(
+ ReconstructXMLDsigAfterAnalysisParameters reconstructXMLDsigParameters)
+ throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(reconstructXMLDsigParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performReconstructXMLDSIG(reconstructXMLDsigParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ // only log in case of error
+ if (sd.isError()) {
+ statLog.log(sd);
+ }
+ }
+ }
+
+ private ReconstructXMLDsigResult performReconstructXMLDSIG(
ReconstructXMLDsigAfterAnalysisParameters reconstructXMLDsigParameters)
throws PdfAsException {
-
+
AnalyzeResult ar = reconstructXMLDsigParameters.getAnalyzeResult();
List extendedSignatureInfos = new Vector();
for (int i = 0; i < ar.getSignatures().size(); i++)
@@ -572,31 +708,52 @@ public class PdfAsObject implements PdfAs
// don't care for connector exceptions because of mutli signs. they are handled during verify
extendedSignatureInfos.add(new ExtendedSignatureInformation(si, null));
}
-
+
}
return new ReconstructXMLDsigResult(extendedSignatureInfos, reconstructXMLDsigParameters.getSignatureDevice());
}
+ public VerifyResults verify(VerifyAfterReconstructXMLDsigParameters verifyAfterReconstructXMLDsigParameters)
+ throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(verifyAfterReconstructXMLDsigParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performVerify(verifyAfterReconstructXMLDsigParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ statLog.log(sd);
+ }
+ }
+
/**
* @see PdfAs#verify(VerifyAfterReconstructXMLDsigParameters)
*/
- public VerifyResults verify(
+ private VerifyResults performVerify(
VerifyAfterReconstructXMLDsigParameters verifyAfterReconstructXMLDsigParameters)
throws PdfAsException {
-
+
try {
List extSignatures = verifyAfterReconstructXMLDsigParameters.getReconstructXMLDsigResult().getExtendedSignatures();
String signatureDevice = verifyAfterReconstructXMLDsigParameters.getSignatureDevice();
if (signatureDevice == null){
signatureDevice = verifyAfterReconstructXMLDsigParameters.getReconstructXMLDsigResult().getDevice();
}
- List results = PdfAS.verifyExtendedSignatureHolders(extSignatures,
- signatureDevice,
- verifyAfterReconstructXMLDsigParameters.isReturnHashInputData(),
+ List results = PdfAS.verifyExtendedSignatureHolders(extSignatures,
+ signatureDevice,
+ verifyAfterReconstructXMLDsigParameters.isReturnHashInputData(),
verifyAfterReconstructXMLDsigParameters.getVerificationTime(), verifyAfterReconstructXMLDsigParameters.getVerifySignatureIndex());
-
+
List vrs = new ArrayList(results.size());
-
+
int verifySignatureIndex = verifyAfterReconstructXMLDsigParameters.getVerifySignatureIndex();
if (verifySignatureIndex < 0)
{
@@ -605,23 +762,23 @@ public class PdfAsObject implements PdfAs
SignatureResponse response = (SignatureResponse) results.get(i);
ExtendedSignatureInformation extSigInfo = (ExtendedSignatureInformation)extSignatures.get(i);
SignatureHolder holder = (SignatureHolder) extSigInfo.getSignatureInformation().getInternalSignatureInformation();
-
+
VerifyResult vr = new VerifyResultAdapter(response, holder, verifyAfterReconstructXMLDsigParameters.getVerificationTime(), extSigInfo.getXmlDsigData());
vr.setNonTextualObjects( extSigInfo.getSignatureInformation().getNonTextualObjects());
-
+
vrs.add(vr);
}
}else{
SignatureResponse response = (SignatureResponse) results.get(0);
ExtendedSignatureInformation extSigInfo = (ExtendedSignatureInformation)extSignatures.get(verifySignatureIndex);
SignatureHolder holder = (SignatureHolder) extSigInfo.getSignatureInformation().getInternalSignatureInformation();
-
+
VerifyResult vr = new VerifyResultAdapter(response, holder, verifyAfterReconstructXMLDsigParameters.getVerificationTime(), extSigInfo.getXmlDsigData());
vr.setNonTextualObjects( extSigInfo.getSignatureInformation().getNonTextualObjects());
-
+
vrs.add(vr);
}
-
+
VerifyResultsImpl verifyResults = new VerifyResultsImpl(vrs);
return verifyResults;
} catch (java.lang.OutOfMemoryError e) {
@@ -632,7 +789,7 @@ public class PdfAsObject implements PdfAs
public DynamicSignatureProfile createDynamicSignatureProfile(String parentProfile, DynamicSignatureLifetimeEnum mode) {
return DynamicSignatureProfileImpl.createFromParent(null, parentProfile, mode);
}
-
+
public DynamicSignatureProfile createEmptyDynamicSignatureProfile(DynamicSignatureLifetimeEnum mode) {
return DynamicSignatureProfileImpl.createEmptyProfile(null, mode);
}
@@ -648,19 +805,44 @@ public class PdfAsObject implements PdfAs
public DynamicSignatureProfile createEmptyDynamicSignatureProfile(String myUniqueName,
DynamicSignatureLifetimeEnum mode) {
- return DynamicSignatureProfileImpl.createEmptyProfile(myUniqueName, mode);
+ return DynamicSignatureProfileImpl.createEmptyProfile(myUniqueName, mode);
+ }
+
+ public SignatureDetailInformation prepareSign(SignParameters signParameters) throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(signParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performPrepareSign(signParameters);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ // only log in case of error
+ if (sd.isError()) {
+ statLog.log(sd);
+ }
+ }
}
/**
* @see PdfAs#prepareSign(SignParameters)
*/
- public SignatureDetailInformation prepareSign(SignParameters signParameters) throws PdfAsException {
+ private SignatureDetailInformation performPrepareSign(SignParameters signParameters) throws PdfAsException {
CheckHelper.checkSignParameters(signParameters, true);
-
+
if (signParameters.getProfileOverrideProperties() != null) {
OverridePropertyHolder.setOverrideProps(signParameters.getProfileOverrideProperties());
}
+ PDFASUtils.createPdfReaderCheckingPermissions(signParameters.getDocument());
+
signParameters.setDocument(PdfAS.applyStrictMode(signParameters.getDocument()));
SettingsReader settings = SettingsReader.getInstance();
@@ -730,29 +912,29 @@ public class PdfAsObject implements PdfAs
} else if (fromConfig) {
arguments[0] = "width defined by the profile " + signParameters.getSignatureProfileId();
}
- log.warn(MessageFormat.format(msg, arguments));
+ log.warn(MessageFormat.format(msg, (Object[]) arguments));
}
}
-
+
Signator signator = createSignator(signParameters.getSignatureType());
SignatorInformation signatorInfo = signator.prepareSign(
- new PdfDataSourceAdapter(signParameters.getDocument()),
- signParameters.getSignatureProfileId(),
- pos,
+ new PdfDataSourceAdapter(signParameters.getDocument()),
+ signParameters.getSignatureProfileId(),
+ pos,
signParameters.getTimeStamperImpl());
-
+
SignatureDetailInformationImpl ret = new SignatureDetailInformationImpl();
ret.setSignatorInformation(signatorInfo);
return ret;
}
-
+
private SignaturePlaceholderData getSignaturePlaceholder(SignParameters signParameters,
String defaultProfile) throws SettingsException, PDFDocumentException, PlaceholderExtractionException {
SignaturePlaceholderData spd = null;
SignaturePlaceholderContext.setSignaturePlaceholderData(null);
-
+
SettingsReader settings = SettingsReader.getInstance();
// check sig_obj.PROFILEID.enable_placeholder_search
@@ -766,15 +948,15 @@ public class PdfAsObject implements PdfAs
// check global enable_placeholder_search
configFileActivedString = settings.getValueFromKey(ENABLE_PLACEHOLDER_SEARCH_KEY);
}
-
+
Boolean configFileActived = null;
if (configFileActivedString != null)
configFileActived = Boolean.valueOf(configFileActivedString);
Boolean signParamsActivated = signParameters.isCheckForPlaceholder();
-
+
boolean enableSearch;
-
+
if (signParamsActivated != null)
{
enableSearch = signParamsActivated.booleanValue();
@@ -788,8 +970,8 @@ public class PdfAsObject implements PdfAs
if (enableSearch)
{
spd = SignaturePlaceholderExtractor.extract(
- signParameters.getDocument().createInputStream(),
- signParameters.getPlaceholderId(),
+ signParameters.getDocument().createInputStream(),
+ signParameters.getPlaceholderId(),
signParameters.getPlaceholderMatchMode());
}
return spd;
@@ -809,15 +991,36 @@ public class PdfAsObject implements PdfAs
{
signatorId = SignatorFactory.MOST_RECENT_DETACHEDTEXT_SIGNATOR_ID;
}
-
+
return at.gv.egiz.pdfas.framework.SignatorFactory.createSignator(signatorId);
}
- public SignResult sign(SignParameters signParameters, SignatureDetailInformation signatorInfo)
+ public SignResult sign(SignParameters signParameters, SignatureDetailInformation signatorInfo)
+ throws PdfAsException {
+ // prepare log data
+ StatisticData sd = new StatisticData(signParameters);
+ StopWatch sw = new StopWatch();
+ try {
+ sw.start();
+ return performSign(signParameters, signatorInfo);
+ } catch (PdfAsException e) {
+ sd.setException(e);
+ throw e;
+ } catch (RuntimeException e) {
+ sd.setException(e);
+ throw e;
+ } finally {
+ sw.stop();
+ sd.setDuration(sw.getTime());
+ statLog.log(sd);
+ }
+ }
+
+ private SignResult performSign(SignParameters signParameters, SignatureDetailInformation signatorInfo)
throws PdfAsException {
CheckHelper.checkSignParametersForSignAfterPrepare(signParameters, false);
-
+
if (signParameters.getProfileOverrideProperties() != null) {
OverridePropertyHolder.setOverrideProps(signParameters.getProfileOverrideProperties());
}
@@ -832,34 +1035,34 @@ public class PdfAsObject implements PdfAs
SignatureData sd = new SignatureDataImpl(new PdfDataSourceAdapter(signatorInfo.getSignatureData()), signatorInfo.getSignatureData().getMimeType());
SignSignatureObject sso = PdfAS.sign(sd, c, signParameters.getTimeStamperImpl());
((SignatureDetailInformationImpl)signatorInfo).setSignSignatureObject(sso);
-
+
return finishSign(signParameters, signatorInfo);
}
- public SignResult finishSign(SignParameters signParameters, SignatureDetailInformation signatureDetailInformation)
+ public SignResult finishSign(SignParameters signParameters, SignatureDetailInformation signatureDetailInformation)
throws PdfAsException {
try {
CheckHelper.checkSignParametersForSignAfterPrepare(signParameters, true);
CheckHelper.checkSignatureDetailInformation(signatureDetailInformation);
-
+
if (signParameters.getProfileOverrideProperties() != null) {
OverridePropertyHolder.setOverrideProps(signParameters.getProfileOverrideProperties());
}
-
+
Signator signator = createSignator(signParameters.getSignatureType());
SignatorInformation signatorInfo = ((SignatureDetailInformationImpl)signatureDetailInformation).getSignatorInfo();
signator.finishSign(signatorInfo, new DataSinkAdapter(signParameters.getOutput()));
return new SignResultImpl(
- signParameters.getOutput(),
+ signParameters.getOutput(),
signatorInfo.getSignSignatureObject().getX509Certificate(),
- new ActualSignaturePositionAdapter(signatorInfo.getActualTablePos()),
+ new ActualSignaturePositionAdapter(signatorInfo.getActualTablePos()),
signatorInfo.getNonTextualObjects());
} finally {
OverridePropertyHolder.removeProperties();
DynamicSignatureProfileImpl.disposeLocalProfile();
}
}
-
+
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/DataSinkAdapter.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/DataSinkAdapter.java
index 2aee44f..b91d5a9 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/DataSinkAdapter.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/DataSinkAdapter.java
@@ -30,7 +30,7 @@ import at.gv.egiz.pdfas.api.io.DataSink;
/**
* Adapter that converts an API DataSink to a framework DataSink.
- *
+ *
* @author wprinz
*/
public class DataSinkAdapter implements at.gv.egiz.pdfas.framework.output.DataSink
@@ -42,7 +42,7 @@ public class DataSinkAdapter implements at.gv.egiz.pdfas.framework.output.DataSi
/**
* Constructor.
- *
+ *
* @param apiDataSink
* The API DataSink to be adapted to a framework DataSink.
*/
@@ -62,7 +62,6 @@ public class DataSinkAdapter implements at.gv.egiz.pdfas.framework.output.DataSi
}
catch (IOException e)
{
- e.printStackTrace();
throw new RuntimeException(e);
}
}
@@ -79,7 +78,6 @@ public class DataSinkAdapter implements at.gv.egiz.pdfas.framework.output.DataSi
}
catch (IOException e)
{
- e.printStackTrace();
throw new RuntimeException(e);
}
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/SignatureProfileImpl.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/SignatureProfileImpl.java
index 35d8c17..1df1a65 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/SignatureProfileImpl.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/api/commons/SignatureProfileImpl.java
@@ -28,6 +28,7 @@ import java.util.Properties;
import org.apache.commons.lang.builder.ToStringBuilder;
import at.gv.egiz.pdfas.api.commons.SignatureProfile;
+import at.knowcenter.wag.egov.egiz.sig.SignatureTypes.State;
/**
* Holds the data of a signature profile.
@@ -61,6 +62,13 @@ public class SignatureProfileImpl implements SignatureProfile {
* true if this is the default profile, false otherwise.
*/
protected boolean defaultProfile = false;
+
+ /**
+ * The state of the signature profile. Signature profiles may be disabled (OFF), allowed for signature only
+ * (SIGN_ONLY), allowed for verification only (VERIFY_ONLY) or just enabled (ON).
+ * Default value here of ON in order to assure backward compatibility.
+ */
+ private State state = State.ON;
/**
* Constructor.
@@ -88,13 +96,25 @@ public class SignatureProfileImpl implements SignatureProfile {
* @param isDefault
*/
public SignatureProfileImpl(String profileId, String profileDescription, String moaKeyIdentifier, boolean isDefault) {
- this.profileId = profileId;
- this.moaKeyIdentifier = moaKeyIdentifier;
- this.profileDescription = profileDescription;
- this.signatureBlockEntries = new Properties();
- this.defaultProfile = isDefault;
+ this(profileId, moaKeyIdentifier);
+ this.profileDescription = profileDescription;
+ this.defaultProfile = isDefault;
}
+ /**
+ * Creates a new signature profile instance.
+ * @param profileId The profile identifier.
+ * @param state The profile's state.
+ * @param profileDescription The profile description.
+ * @param moaKeyIdentifier The MOA-SS key identifier.
+ * @param isDefault {@code true} if this is a default profile, {@code false} if not.
+ */
+ public SignatureProfileImpl(String profileId, State state, String profileDescription, String moaKeyIdentifier, boolean isDefault) {
+ this(profileId, profileDescription, moaKeyIdentifier, isDefault);
+ this.state = state;
+ }
+
+
/**
* @see at.gv.egiz.pdfas.api.commons.SignatureProfile#getProfileId()
*/
@@ -140,19 +160,22 @@ public class SignatureProfileImpl implements SignatureProfile {
return this.profileDescription;
}
- public String toString() {
- return new ToStringBuilder(this)
- .append("profileId", this.profileId)
- .append("profileDescription", this.profileDescription)
- .append("moaKeyIdentifier", this.moaKeyIdentifier)
- .toString();
- }
+ @Override
+ public String toString() {
+ return "SignatureProfileImpl [profileId=" + profileId + ", state=" + state + ", profileDescription="
+ + profileDescription + ", moaKeyIdentifier=" + moaKeyIdentifier + ", defaultProfile=" + defaultProfile
+ + "]";
+ }
- /**
+/**
*
*/
public boolean isDefault() {
return this.defaultProfile;
}
+ public State getState() {
+ return state;
+ }
+
}
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/input/correction/InternalCorrector.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/input/correction/InternalCorrector.java
index eaa6b7f..b193936 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/input/correction/InternalCorrector.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/input/correction/InternalCorrector.java
@@ -26,6 +26,7 @@ package at.gv.egiz.pdfas.impl.input.correction;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
+import at.gv.egiz.pdfas.api.io.DataSource;
import at.gv.egiz.pdfas.exceptions.ErrorCode;
import at.gv.egiz.pdfas.exceptions.framework.CorrectorException;
import at.gv.egiz.pdfas.framework.input.PdfDataSource;
@@ -40,7 +41,7 @@ import com.lowagie.text.pdf.PdfStamper;
/**
* Corrects a document using iText.
- *
+ *
* @author wprinz
*/
public class InternalCorrector implements Corrector
@@ -53,11 +54,9 @@ public class InternalCorrector implements Corrector
{
try
{
- byte[] pdf = document.getAsByteArray();
- PdfReader reader = new PdfReader(pdf);
- PDFASUtils.checkReaderPermissions(reader);
+ PdfReader reader = PDFASUtils.createPdfReaderCheckingPermissions(document);
- ByteArrayOutputStream baos = new ByteArrayOutputStream(pdf.length);
+ ByteArrayOutputStream baos = new ByteArrayOutputStream(document.getLength());
PdfStamper stamper = new PdfStamper(reader, baos, '\0', false);
stamper.close();
diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/signator/binary/BinarySignator_1_0_0.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/signator/binary/BinarySignator_1_0_0.java
index 0af6538..a3ff856 100644
--- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/signator/binary/BinarySignator_1_0_0.java
+++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/signator/binary/BinarySignator_1_0_0.java
@@ -83,7 +83,7 @@ import com.lowagie.text.pdf.PdfPTable;
/**
* Signs the document binary.
- *
+ *
*
* IU blocks without an egiz dict are not considered. *
- * + * * @param pdf * @param blocks * @return Returns the List of signature holders. @@ -673,7 +673,7 @@ public class VerificationFilterImpl implements VerificationFilter String binary_only = settings.getSetting(BINARY_ONLY, "false"); String assume_sigs_only = settings.getSetting(ASSUME_ONLY_SIGNATURE_BLOCKS, "false"); boolean supressException = "true".equalsIgnoreCase(settings.getSetting(SUPRESS_EXCEPTION_WHEN_LAST_UIBLOCK_IS_NO_SIGNATURE, "false")); - + try { // PERF: extract binary signatures needs byte array @@ -689,15 +689,15 @@ public class VerificationFilterImpl implements VerificationFilter FooterParseResult fpr = (FooterParseResult) it.next(); assert fpr.next_index > prev_end; - if (VerificationFilterBinaryHelper.containsEGIZDict(data, fpr)) + PdfASID kz = null; + if (VerificationFilterBinaryHelper.containsEGIZDict(data, fpr) && + (kz = VerificationFilterBinaryHelper.extractKZFromEGIZBlock(data, fpr)) != null) { - PdfASID kz = VerificationFilterBinaryHelper.extractKZFromEGIZBlock(data, fpr); - // TODO dferbas hack baik test //kz = new PdfASID("urn:pdfsigfilter:bka.gv.at:binaer:v1.1.0"); - + Verificator verificator = VerificatorFactory.createBinaryVerificator(kz); - List binary_holders = verificator.parseBlock(pdf, data, fpr, prev_end); + List binary_holders = verificator.parseBlock(pdf, data, fpr, prev_end); binarySignatures.addAll(binary_holders); if(binary_holders.size() > 0) { @@ -707,21 +707,21 @@ public class VerificationFilterImpl implements VerificationFilter // an Exception is thrown here if: // 1) check_document is activated // 2) assume_only_signature_blocks is false - otherwise we permit updates - // 3) binary_only is true - otherwise updates are handled in method performFullConservative(). - // when binary-only is true, we can be sure that a block that contains no egiz-dict is no textual + // 3) binary_only is true - otherwise updates are handled in method performFullConservative(). + // when binary-only is true, we can be sure that a block that contains no egiz-dict is no textual // signature either but an illegal update, otherwise an Exception (doc contains textual sig) would have been thrown before // 4) a binary signature has been detected in a previous block - if(check_doc.equalsIgnoreCase("true") && + if(check_doc.equalsIgnoreCase("true") && binary_only.equalsIgnoreCase("true") && assume_sigs_only.equalsIgnoreCase("false") && - sig_detected) { - + sig_detected) { + if (!supressException) { - throw new VerificationFilterException(ErrorCode.MODIFIED_AFTER_SIGNATION, "The document has been modified after being signed."); + throw new VerificationFilterException(ErrorCode.MODIFIED_AFTER_SIGNATION, "The document has been modified after being signed."); } else { log.debug("The document has been modified after being signed. According to the configuration, no exception is thrown."); } - + } } @@ -749,7 +749,7 @@ public class VerificationFilterImpl implements VerificationFilter List extractedSignatures = extractNewSignaturesFromText(extractedText); log.debug("Extracting signatures finished."); log.debug("Number of found signatures: " + extractedSignatures.size()); - + if (extractedSignatures.size() > 0) { List cp1252SignaturesPositions = new ArrayList(); //boolean iscp1252Sig = false; @@ -760,19 +760,19 @@ public class VerificationFilterImpl implements VerificationFilter log.debug("found cp1252 signature"); cp1252SignaturesPositions.add(new Integer(i)); //iscp1252Sig = true; - //break; + //break; } - } + } if (cp1252SignaturesPositions.size() > 0) { log.debug("redo text and signature extraction with cp1252 encoding"); extractedText = extractText(pdf, endOfDocument, "cp1252"); log.debug("Extracting text finished."); - + log.debug("Extracting signatures:"); List cp1252ExtractedSignatures = extractNewSignaturesFromText(extractedText); log.debug("Extracting signatures finished."); log.debug("Number of found signatures: " + extractedSignatures.size()); - + if (cp1252ExtractedSignatures.size() != extractedSignatures.size()) { log.error("Invalid cp1252 signatures found. Skipping cp1252 compatibility."); } @@ -780,12 +780,12 @@ public class VerificationFilterImpl implements VerificationFilter for (int i = 0; i < cp1252SignaturesPositions.size(); i++) { int replaceIndex = ((Integer)cp1252SignaturesPositions.get(i)).intValue(); extractedSignatures.remove(replaceIndex); - extractedSignatures.add(replaceIndex, cp1252ExtractedSignatures.get(replaceIndex)); + extractedSignatures.add(replaceIndex, cp1252ExtractedSignatures.get(replaceIndex)); } } - + } - + if (log.isDebugEnabled()) { log.debug("extracted signatures:"); @@ -856,7 +856,7 @@ public class VerificationFilterImpl implements VerificationFilter } protected void checkBinaryOnly(PdfDataSource pdf, boolean considerOldSigs) throws VerificationFilterException { - + DelimitedPdfDataSource dds = new DelimitedPdfDataSource(pdf, pdf.getLength()); String text = null; try { @@ -864,10 +864,10 @@ public class VerificationFilterImpl implements VerificationFilter } catch (PresentableException e) { throw new VerificationFilterException(e); } - + List sigs = new ArrayList(); - - if(considerOldSigs) { + + if(considerOldSigs) { SignaturesAndOld sao = extractSignaturesAndOld(text); if(sao != null) { if(sao.newSignatures != null) { @@ -877,30 +877,30 @@ public class VerificationFilterImpl implements VerificationFilter sigs.add(sao.oldSignature); } } - } else { + } else { List signatures = extractSignatures(pdf, pdf.getLength()); if(signatures != null) { sigs.addAll(signatures); } } - + Iterator it = sigs.iterator(); while(it.hasNext()) { SignatureHolder current = (SignatureHolder)it.next(); if((current != null)&&(!current.getSignatureObject().isBinary())) { throw new VerificationFilterException(ErrorCode.NON_BINARY_SIGNATURES_PRESENT, "The document contains non-binary signatures."); } - } + } } - - + + protected static class SignaturesAndOld { public List newSignatures = null; public SignatureHolder oldSignature = null; } - + protected SignaturesAndOld extractSignaturesAndOld(String text) throws VerificationFilterException { try @@ -908,7 +908,7 @@ public class VerificationFilterImpl implements VerificationFilter log.debug("Extracting signatures:"); List extractedSignatures = extractNewSignaturesFromText(text); log.debug("Extracting signatures finished."); - + log.debug("Extracting old signatures:"); SignatureHolder oldSignature = extractOldSignature(text, extractedSignatures); log.debug("Extracting old signatures finished."); @@ -929,7 +929,7 @@ public class VerificationFilterImpl implements VerificationFilter /** * Extracts the old signature from the text, but only if it is older than the * oldest signature of the new signatueres. - * + * * @param extractedText * @param newSignatures * @return diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/vfilter/helper/VerificationFilterBinaryHelper.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/vfilter/helper/VerificationFilterBinaryHelper.java index 735b874..3093c36 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/vfilter/helper/VerificationFilterBinaryHelper.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/impl/vfilter/helper/VerificationFilterBinaryHelper.java @@ -48,7 +48,7 @@ import at.knowcenter.wag.exactparser.parsing.results.ObjectParseResult; /** * Contains helpful methods used by the VerificationFilter to analyze the PDF for binary signatures. - * + * * @author wprinz */ public final class VerificationFilterBinaryHelper @@ -70,12 +70,12 @@ public final class VerificationFilterBinaryHelper /** * Tells, if the given incremental update block contains a binary signature. - * + * ** According to definition, if a block is a binary block, it must/cannot * contain other signatures than this one. *
- * + * * @param block * The incremental update block. * @return Returns true, if this block is a binary signature block, false @@ -94,7 +94,7 @@ public final class VerificationFilterBinaryHelper /** * Extracts the PDF AS ID of the egiz block. - * + * * @param pdf * The pdf. * @param block @@ -120,6 +120,13 @@ public final class VerificationFilterBinaryHelper IndirectObjectReference ior = egiz_dict_iorpr.ior; final int egiz_dict_offset = PDFUtils.getObjectOffsetFromXRefByIndirectObjectReference(block.xpr, ior); + + // fix dti: + if (egiz_dict_offset < 0) { + log.debug("Current ui block contains a /EGIZSigDict trailer entry but no respective xref table entry. This indicates that this ui block does not contain binary signatures."); + return null; + } + // logger_.debug("egiz_dict_offset = " + egiz_dict_offset); ObjectParseResult obj = PDFUtils.parseObject(pdf, egiz_dict_offset); @@ -140,7 +147,7 @@ public final class VerificationFilterBinaryHelper /** * Restores the Kennzeichnung String from an Array. - * + * * @param pdf * The PDF. * @param kz_apr @@ -174,7 +181,7 @@ public final class VerificationFilterBinaryHelper si.pdf = pdf; log.trace("Adding KZ: " + si.toString()); - + partition.add(si); } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/FileBasedTextBasedDataSource.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/FileBasedTextBasedDataSource.java index aaf99ea..918b13d 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/FileBasedTextBasedDataSource.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/FileBasedTextBasedDataSource.java @@ -33,7 +33,7 @@ import at.gv.egiz.pdfas.api.io.TextBased; /** * FileBased DataSource that is TextBased. - * + * * @author wprinz */ public class FileBasedTextBasedDataSource extends FileBasedDataSource implements TextBased @@ -113,7 +113,6 @@ public class FileBasedTextBasedDataSource extends FileBasedDataSource implements } catch (UnsupportedEncodingException e) { - e.printStackTrace(); throw new RuntimeException(e); } } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/StringTextBasedDataSource.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/StringTextBasedDataSource.java index 8fe0dd6..8234b2a 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/StringTextBasedDataSource.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/io/StringTextBasedDataSource.java @@ -32,9 +32,9 @@ import at.gv.egiz.pdfas.api.io.TextBased; /** * A String TextBased DataSource. - * + * * @author wprinz - * + * */ public class StringTextBasedDataSource implements DataSource, TextBased { @@ -74,7 +74,6 @@ public class StringTextBasedDataSource implements DataSource, TextBased } catch (UnsupportedEncodingException e) { - e.printStackTrace(); throw new RuntimeException(e); } } diff --git a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/placeholder/SignaturePlaceholderExtractor.java b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/placeholder/SignaturePlaceholderExtractor.java index 8b8c22e..453b620 100644 --- a/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/placeholder/SignaturePlaceholderExtractor.java +++ b/pdf-as-lib/src/main/java/at/gv/egiz/pdfas/placeholder/SignaturePlaceholderExtractor.java @@ -71,7 +71,7 @@ import com.google.zxing.common.HybridBinarizer; /** * Extract all relevant information from a placeholder image. - * + * * @author exthex * */ @@ -80,10 +80,10 @@ public class SignaturePlaceholderExtractor extends PDFStreamEngine { * The log. */ private static Log log = LogFactory.getLog(SignaturePlaceholderExtractor.class); - + private List placeholders = new Vector(); private int currentPage = 0; - + private SignaturePlaceholderExtractor(String placeholderId, int placeholderMatchMode) throws IOException { super(ResourceLoader.loadProperties("at/gv/egiz/pdfas/placeholder/pdfbox-reader.properties", true)); @@ -93,7 +93,7 @@ public class SignaturePlaceholderExtractor extends PDFStreamEngine { * Search the document for placeholder images and possibly included * additional info.