Digital signatures - chapter 5

This is a code example of iText PDF, discover more.

1st November 2015
admin-marketing

Switch code for this example

C5_01_SignatureIntegrity.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.IOException;
  4. import java.security.GeneralSecurityException;
  5. import java.security.Security;
  6. import java.util.ArrayList;
  7.  
  8. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  9.  
  10. import com.itextpdf.text.log.LoggerFactory;
  11. import com.itextpdf.text.log.SysoLogger;
  12. import com.itextpdf.text.pdf.AcroFields;
  13. import com.itextpdf.text.pdf.PdfReader;
  14. import com.itextpdf.text.pdf.security.PdfPKCS7;
  15.  
  16. public class C5_01_SignatureIntegrity {
  17.     public static final String EXAMPLE1 = "results/chapter2/hello_level_1_annotated_wrong.pdf";
  18.     public static final String EXAMPLE2 = "results/chapter2/step_4_signed_by_alice_bob_carol_and_dave.pdf";
  19.     public static final String EXAMPLE3 = "results/chapter2/step_6_signed_by_dave_broken_by_chuck.pdf";
  20.  
  21.     public PdfPKCS7 verifySignature(AcroFields fields, String name) throws GeneralSecurityException, IOException {
  22.         System.out.println("Signature covers whole document: " + fields.signatureCoversWholeDocument(name));
  23.         System.out.println("Document revision: " + fields.getRevision(name) + " of " + fields.getTotalRevisions());
  24.         PdfPKCS7 pkcs7 = fields.verifySignature(name);
  25.         System.out.println("Integrity check OK? " + pkcs7.verify());
  26.         return pkcs7;
  27.     }
  28.    
  29.     public void verifySignatures(String path) throws IOException, GeneralSecurityException {
  30.         System.out.println(path);
  31.         PdfReader reader = new PdfReader(path);
  32.         AcroFields fields = reader.getAcroFields();
  33.         ArrayList names = fields.getSignatureNames();
  34.         for (String name : names) {
  35.             System.out.println("===== " + name + " =====");
  36.             verifySignature(fields, name);
  37.         }
  38.         System.out.println();
  39.     }
  40.    
  41.     public static void main(String[] args) throws IOException, GeneralSecurityException {
  42.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  43.         BouncyCastleProvider provider = new BouncyCastleProvider();
  44.         Security.addProvider(provider);
  45.         C5_01_SignatureIntegrity app = new C5_01_SignatureIntegrity();
  46.         app.verifySignatures(EXAMPLE1);
  47.         app.verifySignatures(EXAMPLE2);
  48.         app.verifySignatures(EXAMPLE3);
  49.     }
  50. }
C5_02_SignatureInfo.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.IOException;
  4. import java.security.GeneralSecurityException;
  5. import java.security.Security;
  6. import java.security.cert.X509Certificate;
  7. import java.text.SimpleDateFormat;
  8. import java.util.ArrayList;
  9. import java.util.List;
  10.  
  11. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  12. import org.bouncycastle.tsp.TimeStampToken;
  13.  
  14. import com.itextpdf.text.Rectangle;
  15. import com.itextpdf.text.log.LoggerFactory;
  16. import com.itextpdf.text.log.SysoLogger;
  17. import com.itextpdf.text.pdf.AcroFields;
  18. import com.itextpdf.text.pdf.AcroFields.FieldPosition;
  19. import com.itextpdf.text.pdf.PdfDictionary;
  20. import com.itextpdf.text.pdf.PdfName;
  21. import com.itextpdf.text.pdf.PdfReader;
  22. import com.itextpdf.text.pdf.PdfString;
  23. import com.itextpdf.text.pdf.security.CertificateInfo;
  24. import com.itextpdf.text.pdf.security.PdfPKCS7;
  25. import com.itextpdf.text.pdf.security.SignaturePermissions;
  26. import com.itextpdf.text.pdf.security.SignaturePermissions.FieldLock;
  27.  
  28. public class C5_02_SignatureInfo extends C5_01_SignatureIntegrity {
  29.     public static final String EXAMPLE1 = "results/chapter2/step_4_signed_by_alice_bob_carol_and_dave.pdf";
  30.     public static final String EXAMPLE2 = "results/chapter3/hello_cacert_ocsp_ts.pdf";
  31.     public static final String EXAMPLE3 = "results/chapter3/hello_token.pdf";
  32.     public static final String EXAMPLE4 = "results/chapter2/hello_signed4.pdf";
  33.     public static final String EXAMPLE5 = "results/chapter4/hello_smartcard_Signature.pdf";
  34.     public static final String EXAMPLE6 = "results/chapter2/field_metadata.pdf";
  35.  
  36.     public SignaturePermissions inspectSignature(AcroFields fields, String name, SignaturePermissions perms) throws GeneralSecurityException, IOException {
  37.         List fps = fields.getFieldPositions(name);
  38.         if (fps != null && fps.size() > 0) {
  39.             FieldPosition fp = fps.get(0);
  40.             Rectangle pos = fp.position;
  41.             if (pos.getWidth() == 0 || pos.getHeight() == 0) {
  42.                 System.out.println("Invisible signature");
  43.             }
  44.             else {
  45.                 System.out.println(String.format("Field on page %s; llx: %s, lly: %s, urx: %s; ury: %s",
  46.                     fp.page, pos.getLeft(), pos.getBottom(), pos.getRight(), pos.getTop()));
  47.             }
  48.         }
  49.        
  50.         PdfPKCS7 pkcs7 = super.verifySignature(fields, name);
  51.         System.out.println("Digest algorithm: " + pkcs7.getHashAlgorithm());
  52.         System.out.println("Encryption algorithm: " + pkcs7.getEncryptionAlgorithm());
  53.         System.out.println("Filter subtype: " + pkcs7.getFilterSubtype());
  54.         X509Certificate cert = (X509Certificate) pkcs7.getSigningCertificate();
  55.             System.out.println("Name of the signer: " + CertificateInfo.getSubjectFields(cert).getField("CN"));
  56.         if (pkcs7.getSignName() != null)
  57.             System.out.println("Alternative name of the signer: " + pkcs7.getSignName());
  58.         SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
  59.         System.out.println("Signed on: " + date_format.format(pkcs7.getSignDate().getTime()));
  60.         if (pkcs7.getTimeStampDate() != null) {
  61.             System.out.println("TimeStamp: " + date_format.format(pkcs7.getTimeStampDate().getTime()));
  62.             TimeStampToken ts = pkcs7.getTimeStampToken();
  63.             System.out.println("TimeStamp service: " + ts.getTimeStampInfo().getTsa());
  64.             System.out.println("Timestamp verified? " + pkcs7.verifyTimestampImprint());
  65.         }
  66.         System.out.println("Location: " + pkcs7.getLocation());
  67.         System.out.println("Reason: " + pkcs7.getReason());
  68.         PdfDictionary sigDict = fields.getSignatureDictionary(name);
  69.         PdfString contact = sigDict.getAsString(PdfName.CONTACTINFO);
  70.         if (contact != null)
  71.             System.out.println("Contact info: " + contact);
  72.         perms = new SignaturePermissions(sigDict, perms);
  73.         System.out.println("Signature type: " + (perms.isCertification() ? "certification" : "approval"));
  74.         System.out.println("Filling out fields allowed: " + perms.isFillInAllowed());
  75.         System.out.println("Adding annotations allowed: " + perms.isAnnotationsAllowed());
  76.         for (FieldLock lock : perms.getFieldLocks()) {
  77.             System.out.println("Lock: " + lock.toString());
  78.         }
  79.         return perms;
  80.     }
  81.    
  82.     public void inspectSignatures(String path) throws IOException, GeneralSecurityException {
  83.         System.out.println(path);
  84.         PdfReader reader = new PdfReader(path);
  85.         AcroFields fields = reader.getAcroFields();
  86.         ArrayList names = fields.getSignatureNames();
  87.         SignaturePermissions perms = null;
  88.         for (String name : names) {
  89.             System.out.println("===== " + name + " =====");
  90.             perms = inspectSignature(fields, name, perms);
  91.         }
  92.         System.out.println();
  93.     }
  94.    
  95.     public static void main(String[] args) throws IOException, GeneralSecurityException {
  96.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  97.         BouncyCastleProvider provider = new BouncyCastleProvider();
  98.         Security.addProvider(provider);
  99.         C5_02_SignatureInfo app = new C5_02_SignatureInfo();
  100.         app.inspectSignatures(EXAMPLE1);
  101.         app.inspectSignatures(EXAMPLE2);
  102.         app.inspectSignatures(EXAMPLE3);
  103.         app.inspectSignatures(EXAMPLE4);
  104.         app.inspectSignatures(EXAMPLE5);
  105.         app.inspectSignatures(EXAMPLE6);
  106.     }
  107. }
C5_03_CertificateValidation.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.security.GeneralSecurityException;
  6. import java.security.KeyStore;
  7. import java.security.Security;
  8. import java.security.cert.CRL;
  9. import java.security.cert.Certificate;
  10. import java.security.cert.CertificateExpiredException;
  11. import java.security.cert.CertificateFactory;
  12. import java.security.cert.CertificateNotYetValidException;
  13. import java.security.cert.X509CRL;
  14. import java.security.cert.X509Certificate;
  15. import java.text.SimpleDateFormat;
  16. import java.util.ArrayList;
  17. import java.util.Calendar;
  18. import java.util.Date;
  19. import java.util.List;
  20.  
  21. import org.bouncycastle.cert.ocsp.BasicOCSPResp;
  22. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  23.  
  24. import com.itextpdf.text.log.LoggerFactory;
  25. import com.itextpdf.text.log.SysoLogger;
  26. import com.itextpdf.text.pdf.AcroFields;
  27. import com.itextpdf.text.pdf.security.CRLVerifier;
  28. import com.itextpdf.text.pdf.security.CertificateVerification;
  29. import com.itextpdf.text.pdf.security.OCSPVerifier;
  30. import com.itextpdf.text.pdf.security.PdfPKCS7;
  31. import com.itextpdf.text.pdf.security.VerificationException;
  32. import com.itextpdf.text.pdf.security.VerificationOK;
  33.  
  34. public class C5_03_CertificateValidation extends C5_01_SignatureIntegrity {
  35.     public static final String ADOBE = "src/main/resources/adobeRootCA.cer";
  36.     public static final String CACERT = "src/main/resources/CACertSigningAuthority.crt";
  37.     public static final String BRUNO = "src/main/resources/bruno.crt";
  38.  
  39.     public static final String EXAMPLE1 = "results/chapter3/hello_cacert_ocsp_ts.pdf";
  40.     public static final String EXAMPLE2 = "results/chapter3/hello_token.pdf";
  41.     public static final String EXAMPLE3 = "results/chapter2/hello_signed1.pdf";
  42.     public static final String EXAMPLE4 = "results/chapter4/hello_smartcard_Signature.pdf";
  43.  
  44.     KeyStore ks;
  45.  
  46.     public PdfPKCS7 verifySignature(AcroFields fields, String name)
  47.             throws GeneralSecurityException, IOException {
  48.         PdfPKCS7 pkcs7 = super.verifySignature(fields, name);
  49.         Certificate[] certs = pkcs7.getSignCertificateChain();
  50.         Calendar cal = pkcs7.getSignDate();
  51.         List errors = CertificateVerification.verifyCertificates(certs, ks, cal);
  52.         if (errors.size() == 0)
  53.             System.out.println("Certificates verified against the KeyStore");
  54.         else
  55.             System.out.println(errors);
  56.         for (int i = 0; i < certs.length; i++) {
  57.             X509Certificate cert = (X509Certificate) certs[i];
  58.             System.out.println("=== Certificate " + i + " ===");
  59.             showCertificateInfo(cert, cal.getTime());
  60.         }
  61.         X509Certificate signCert = (X509Certificate)certs[0];
  62.         X509Certificate issuerCert = (certs.length > 1 ? (X509Certificate)certs[1] : null);
  63.         System.out.println("=== Checking validity of the document at the time of signing ===");
  64.         checkRevocation(pkcs7, signCert, issuerCert, cal.getTime());
  65.         System.out.println("=== Checking validity of the document today ===");
  66.         checkRevocation(pkcs7, signCert, issuerCert, new Date());
  67.         return pkcs7;
  68.     }
  69.    
  70.     public static void checkRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, Date date) throws GeneralSecurityException, IOException {
  71.         List ocsps = new ArrayList();
  72.         if (pkcs7.getOcsp() != null)
  73.             ocsps.add(pkcs7.getOcsp());
  74.         OCSPVerifier ocspVerifier = new OCSPVerifier(null, ocsps);
  75.         List verification =
  76.             ocspVerifier.verify(signCert, issuerCert, date);
  77.         if (verification.size() == 0) {
  78.             List crls = new ArrayList();
  79.             if (pkcs7.getCRLs() != null) {
  80.                 for (CRL crl : pkcs7.getCRLs())
  81.                     crls.add((X509CRL)crl);
  82.             }
  83.             CRLVerifier crlVerifier = new CRLVerifier(null, crls);
  84.             verification.addAll(crlVerifier.verify(signCert, issuerCert, date));
  85.         }
  86.         if (verification.size() == 0) {
  87.             System.out.println("The signing certificate couldn't be verified");
  88.         }
  89.         else {
  90.             for (VerificationOK v : verification)
  91.                 System.out.println(v);
  92.         }
  93.     }
  94.  
  95.     public void showCertificateInfo(X509Certificate cert, Date signDate) {
  96.         System.out.println("Issuer: " + cert.getIssuerDN());
  97.         System.out.println("Subject: " + cert.getSubjectDN());
  98.         SimpleDateFormat date_format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SS");
  99.         System.out.println("Valid from: " + date_format.format(cert.getNotBefore()));
  100.         System.out.println("Valid to: " + date_format.format(cert.getNotAfter()));
  101.         try {
  102.             cert.checkValidity(signDate);
  103.             System.out
  104.                     .println("The certificate was valid at the time of signing.");
  105.         } catch (CertificateExpiredException e) {
  106.             System.out
  107.                     .println("The certificate was expired at the time of signing.");
  108.         } catch (CertificateNotYetValidException e) {
  109.             System.out
  110.                     .println("The certificate wasn't valid yet at the time of signing.");
  111.         }
  112.         try {
  113.             cert.checkValidity();
  114.             System.out.println("The certificate is still valid.");
  115.         } catch (CertificateExpiredException e) {
  116.             System.out.println("The certificate has expired.");
  117.         } catch (CertificateNotYetValidException e) {
  118.             System.out.println("The certificate isn't valid yet.");
  119.         }
  120.     }
  121.    
  122.     private void setKeyStore(KeyStore ks) {
  123.         this.ks = ks;
  124.     }
  125.  
  126.     public static void main(String[] args) throws IOException,
  127.             GeneralSecurityException {
  128.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  129.         BouncyCastleProvider provider = new BouncyCastleProvider();
  130.         Security.addProvider(provider);
  131.         C5_03_CertificateValidation app = new C5_03_CertificateValidation();
  132.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  133.  
  134.         ks.load(null, null);
  135.         CertificateFactory cf = CertificateFactory.getInstance("X.509");
  136.         ks.setCertificateEntry("adobe",
  137.                 cf.generateCertificate(new FileInputStream(ADOBE)));
  138.         ks.setCertificateEntry("cacert",
  139.                 cf.generateCertificate(new FileInputStream(CACERT)));
  140.         ks.setCertificateEntry("bruno",
  141.                 cf.generateCertificate(new FileInputStream(BRUNO)));
  142.         app.setKeyStore(ks);
  143.         app.verifySignatures(EXAMPLE1);
  144.         app.verifySignatures(EXAMPLE2);
  145.         app.verifySignatures(EXAMPLE3);
  146.         app.verifySignatures(EXAMPLE4);
  147.     }
  148. }
C5_04_LTV.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.security.GeneralSecurityException;
  7. import java.security.Security;
  8. import java.util.List;
  9. import java.util.Properties;
  10.  
  11. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  12.  
  13. import com.itextpdf.text.DocumentException;
  14. import com.itextpdf.text.log.LoggerFactory;
  15. import com.itextpdf.text.log.SysoLogger;
  16. import com.itextpdf.text.pdf.AcroFields;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20. import com.itextpdf.text.pdf.security.CrlClient;
  21. import com.itextpdf.text.pdf.security.CrlClientOnline;
  22. import com.itextpdf.text.pdf.security.LtvTimestamp;
  23. import com.itextpdf.text.pdf.security.LtvVerification;
  24. import com.itextpdf.text.pdf.security.OcspClient;
  25. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  26. import com.itextpdf.text.pdf.security.PdfPKCS7;
  27. import com.itextpdf.text.pdf.security.TSAClient;
  28. import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
  29.  
  30. public class C5_04_LTV {
  31.  
  32.     public static final String EXAMPLE1 = "results/chapter3/hello_token.pdf";
  33.     public static final String EXAMPLE2 = "results/chapter4/hello_smartcard_Signature.pdf";
  34.     public static final String EXAMPLE3 = "results/chapter3/hello_cacert_ocsp_ts.pdf";
  35.     public static final String DEST = "results/chapter5/ltv_%s.pdf";
  36.    
  37.     public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
  38.         Security.addProvider(new BouncyCastleProvider());
  39.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  40.         Properties properties = new Properties();
  41.         properties.load(new FileInputStream("c:/home/blowagie/key.properties"));
  42.         String tsaUrl = properties.getProperty("TSAURL");
  43.         String tsaUser = properties.getProperty("TSAUSERNAME");
  44.         String tsaPass = properties.getProperty("TSAPASSWORD");
  45.         C5_04_LTV app = new C5_04_LTV();
  46.         TSAClient tsa = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass, 6500, "SHA512");
  47.         OcspClient ocsp = new OcspClientBouncyCastle();
  48.         app.addLtv(EXAMPLE1, String.format(DEST, 1), ocsp, new CrlClientOnline(), tsa);
  49.         System.out.println();
  50.         app.addLtv(EXAMPLE2, String.format(DEST, 2), ocsp, new CrlClientOnline(), tsa);
  51.         System.out.println();
  52.         app.addLtv(EXAMPLE3, String.format(DEST, 3), ocsp, new CrlClientOnline(), tsa);
  53.         System.out.println();
  54.         app.addLtv(String.format(DEST, 1), String.format(DEST, 4), null, new CrlClientOnline(), tsa);
  55.     }
  56.    
  57.     public void addLtv(String src, String dest, OcspClient ocsp, CrlClient crl, TSAClient tsa) throws IOException, DocumentException, GeneralSecurityException {
  58.         PdfReader r = new PdfReader(src);
  59.         FileOutputStream fos = new FileOutputStream(dest);
  60.         PdfStamper stp = PdfStamper.createSignature(r, fos, '\0', null, true);
  61.         LtvVerification v = stp.getLtvVerification();
  62.         AcroFields fields = stp.getAcroFields();
  63.         List names = fields.getSignatureNames();
  64.         String sigName = names.get(names.size() - 1);
  65.         PdfPKCS7 pkcs7 = fields.verifySignature(sigName);
  66.         if (pkcs7.isTsp())
  67.             System.out.println("TIMESTAMP!");
  68.         for (String name : names) {
  69.             v.addVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
  70.         }
  71.         PdfSignatureAppearance sap = stp.getSignatureAppearance();
  72.         LtvTimestamp.timestamp(sap, tsa, null);
  73.     }
  74. }
C5_05_CheckLTV.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.IOException;
  4. import java.security.GeneralSecurityException;
  5. import java.security.Security;
  6. import java.security.cert.X509Certificate;
  7. import java.util.ArrayList;
  8.  
  9. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  10.  
  11. import com.itextpdf.text.log.LoggerFactory;
  12. import com.itextpdf.text.log.SysoLogger;
  13. import com.itextpdf.text.pdf.AcroFields;
  14. import com.itextpdf.text.pdf.PdfReader;
  15. import com.itextpdf.text.pdf.security.CertificateInfo;
  16. import com.itextpdf.text.pdf.security.PdfPKCS7;
  17.  
  18. public class C5_05_CheckLTV {
  19.     public static final String EXAMPLE1 = "results/chapter5/ltv_1.pdf";
  20.     public static final String EXAMPLE2 = "results/chapter5/ltv_2.pdf";
  21.     public static final String EXAMPLE3 = "results/chapter5/ltv_3.pdf";
  22.     public static final String EXAMPLE4 = "results/chapter5/ltv_4.pdf";
  23.  
  24.     public PdfPKCS7 verifySignature(AcroFields fields, String name) throws GeneralSecurityException, IOException {
  25.         System.out.println("Signature covers whole document: " + fields.signatureCoversWholeDocument(name));
  26.         System.out.println("Document revision: " + fields.getRevision(name) + " of " + fields.getTotalRevisions());
  27.         PdfPKCS7 pkcs7 = fields.verifySignature(name);
  28.         System.out.println("Integrity check OK? " + pkcs7.verify());
  29.         System.out.println("Digest algorithm: " + pkcs7.getHashAlgorithm());
  30.         System.out.println("Encryption algorithm: " + pkcs7.getEncryptionAlgorithm());
  31.         System.out.println("Filter subtype: " + pkcs7.getFilterSubtype());
  32.         X509Certificate cert = (X509Certificate) pkcs7.getSigningCertificate();
  33.         System.out.println("Name of the signer: " + CertificateInfo.getSubjectFields(cert).getField("CN"));
  34.         return pkcs7;
  35.     }
  36.    
  37.     public void verifySignatures(String path) throws IOException, GeneralSecurityException {
  38.         System.out.println(path);
  39.         PdfReader reader = new PdfReader(path);
  40.         AcroFields fields = reader.getAcroFields();
  41.         ArrayList names = fields.getSignatureNames();
  42.         for (String name : names) {
  43.             System.out.println("===== " + name + " =====");
  44.             verifySignature(fields, name);
  45.         }
  46.         System.out.println();
  47.     }
  48.    
  49.     public static void main(String[] args) throws IOException, GeneralSecurityException {
  50.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  51.         BouncyCastleProvider provider = new BouncyCastleProvider();
  52.         Security.addProvider(provider);
  53.         C5_05_CheckLTV app = new C5_05_CheckLTV();
  54.         app.verifySignatures(EXAMPLE1);
  55.         app.verifySignatures(EXAMPLE2);
  56.         app.verifySignatures(EXAMPLE3);
  57.         app.verifySignatures(EXAMPLE4);
  58.     }
  59. }
C5_06_ValidateLTV.java
  1. package signatures.chapter5;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.IOException;
  5. import java.security.GeneralSecurityException;
  6. import java.security.KeyStore;
  7. import java.security.Security;
  8. import java.security.cert.CertificateFactory;
  9. import java.security.cert.X509Certificate;
  10. import java.util.ArrayList;
  11. import java.util.Date;
  12. import java.util.List;
  13.  
  14. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  15.  
  16. import com.itextpdf.text.pdf.PdfReader;
  17. import com.itextpdf.text.pdf.security.CertificateVerifier;
  18. import com.itextpdf.text.pdf.security.LtvVerifier;
  19. import com.itextpdf.text.pdf.security.LtvVerification.CertificateOption;
  20. import com.itextpdf.text.pdf.security.VerificationOK;
  21.  
  22. public class C5_06_ValidateLTV {
  23.     public static final String ADOBE = "src/main/resources/adobeRootCA.cer";
  24.     public static final String EXAMPLE1 = "results/chapter5/ltv_1.pdf";
  25.     public static final String EXAMPLE2 = "results/chapter5/ltv_2.pdf";
  26.     public static final String EXAMPLE3 = "results/chapter5/ltv_3.pdf";
  27.     public static final String EXAMPLE4 = "results/chapter5/ltv_4.pdf";
  28.    
  29.     public static void main(String[] args) throws IOException, GeneralSecurityException {
  30.         BouncyCastleProvider provider = new BouncyCastleProvider();
  31.         Security.addProvider(provider);
  32.         C5_06_ValidateLTV app = new C5_06_ValidateLTV();
  33.         System.out.println(EXAMPLE1);
  34.         app.validate(new PdfReader(EXAMPLE1));
  35.         System.out.println();
  36.         System.out.println(EXAMPLE2);
  37.         app.validate(new PdfReader(EXAMPLE2));
  38.         System.out.println();
  39.         System.out.println(EXAMPLE3);
  40.         app.validate(new PdfReader(EXAMPLE3));
  41.         System.out.println();
  42.         System.out.println(EXAMPLE4);
  43.         app.validate(new PdfReader(EXAMPLE4));
  44.     }
  45.    
  46.     public void validate(PdfReader reader) throws IOException, GeneralSecurityException {
  47.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  48.         ks.load(null, null);
  49.         CertificateFactory cf = CertificateFactory.getInstance("X.509");
  50.         ks.setCertificateEntry("adobe",
  51.                 cf.generateCertificate(new FileInputStream(ADOBE)));
  52.        
  53.         CertificateVerifier custom = new CertificateVerifier(null) {
  54.             public List verify(X509Certificate signCert,
  55.                     X509Certificate issuerCert, Date signDate)
  56.                     throws GeneralSecurityException, IOException {
  57.                 System.out.println(signCert.getSubjectDN().getName() + ": ALL VERIFICATIONS DONE");
  58.                 return new ArrayList();
  59.             }
  60.         };
  61.        
  62.         LtvVerifier data = new LtvVerifier(reader);
  63.         data.setRootStore(ks);
  64.         data.setCertificateOption(CertificateOption.WHOLE_CHAIN);
  65.         data.setVerifier(custom);
  66.         data.setOnlineCheckingAllowed(false);
  67.         data.setVerifyRootCertificate(false);
  68.         List list = new ArrayList();
  69.         try {
  70.             data.verify(list);
  71.         }
  72.         catch(GeneralSecurityException e) {
  73.             System.err.println(e.getMessage());
  74.         }
  75.         System.out.println();
  76.         if (list.size() == 0) {
  77.             System.out.println("The document can't be verified");
  78.         }
  79.         for (VerificationOK v : list)
  80.             System.out.println(v.toString());
  81.     }
  82. }
C5_01_SignatureIntegrity.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using iTextSharp.text.log;
  12. using iTextSharp.text.pdf;
  13. using iTextSharp.text.pdf.security;
  14.  
  15. namespace signatures.chapter5 {
  16.     public class C5_01_SignatureIntegrity {
  17.         public const String EXAMPLE1 = "../../../../results/chapter2/hello_level_1_annotated_wrong.pdf";
  18.         public const String EXAMPLE2 = "../../../../results/chapter2/step_4_signed_by_alice_bob_carol_and_dave.pdf";
  19.         public const String EXAMPLE3 = "../../../../results/chapter2/step_6_signed_by_dave_broken_by_chuck.pdf";
  20.  
  21.         virtual public PdfPKCS7 VerifySignature(AcroFields fields, String name) {
  22.             Console.WriteLine("Signature covers whole document: " + fields.SignatureCoversWholeDocument(name));
  23.             Console.WriteLine("Document revision: " + fields.GetRevision(name) + " of " + fields.TotalRevisions);
  24.             PdfPKCS7 pkcs7 = fields.VerifySignature(name);
  25.             Console.WriteLine("Integrity check OK? " + pkcs7.Verify());
  26.             return pkcs7;
  27.         }
  28.        
  29.         public void VerifySignatures(String path) {
  30.             Console.WriteLine(path);
  31.             PdfReader reader = new PdfReader(path);
  32.             AcroFields fields = reader.AcroFields;
  33.             List names = fields.GetSignatureNames();
  34.             foreach (string name in names) {
  35.                 Console.WriteLine("===== " + name + " =====");
  36.                 VerifySignature(fields, name);
  37.             }
  38.             Console.WriteLine();
  39.         }
  40.        
  41.         public static void Main(String[] args) {
  42.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  43.             C5_01_SignatureIntegrity app = new C5_01_SignatureIntegrity();
  44.             app.VerifySignatures(EXAMPLE1);
  45.             app.VerifySignatures(EXAMPLE2);
  46.             app.VerifySignatures(EXAMPLE3);
  47.         }
  48.     }
  49. }
C5_02_SignatureInfo.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using Org.BouncyCastle.Tsp;
  12. using Org.BouncyCastle.X509;
  13. using iTextSharp.text;
  14. using iTextSharp.text.log;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.pdf.security;
  17.  
  18. namespace signatures.chapter5 {
  19.     class C5_02_SignatureInfo : C5_01_SignatureIntegrity {
  20.         public const String EXAMPLE1 = "../../../../results/chapter2/step_4_signed_by_alice_bob_carol_and_dave.pdf";
  21.         public const String EXAMPLE2 = "../../../../results/chapter3/hello_cacert_ocsp_ts.pdf";
  22.         public const String EXAMPLE3 = "../../../../results/chapter3/hello_token.pdf";
  23.         public const String EXAMPLE4 = "../../../../results/chapter2/hello_signed4.pdf";
  24.         public const String EXAMPLE5 = "../../../../results/chapter4/hello_smartcard_Signature.pdf";
  25.         public const String EXAMPLE6 = "../../../../results/chapter2/field_metadata.pdf";
  26.  
  27.         public SignaturePermissions InspectSignature(AcroFields fields, String name, SignaturePermissions perms) {
  28.             IList fps = fields.GetFieldPositions(name);
  29.             if (fps != null && fps.Count > 0) {
  30.                 AcroFields.FieldPosition fp = fps[0];
  31.                 Rectangle pos = fp.position;
  32.                 if (pos.Width == 0 || pos.Height == 0) {
  33.                     Console.WriteLine("Invisible signature");
  34.                 }
  35.                 else {
  36.                     Console.WriteLine("Field on page {0}; llx: {1}, lly: {2}, urx: {3}; ury: {4}",
  37.                         fp.page, pos.Left, pos.Bottom, pos.Right, pos.Top);
  38.                 }
  39.             }
  40.            
  41.             PdfPKCS7 pkcs7 = VerifySignature(fields, name);
  42.             Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm());
  43.             Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm());
  44.             Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype());
  45.             X509Certificate cert = pkcs7.SigningCertificate;
  46.                 Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN"));
  47.             if (pkcs7.SignName != null)
  48.                 Console.WriteLine("Alternative name of the signer: " + pkcs7.SignName);
  49.            
  50.             Console.WriteLine("Signed on: " + pkcs7.SignDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
  51.             if (!pkcs7.TimeStampDate.Equals(DateTime.MaxValue)) {
  52.                 Console.WriteLine("TimeStamp: " + pkcs7.TimeStampDate.ToString("yyyy-MM-dd HH:mm:ss.ff"));
  53.                 TimeStampToken ts = pkcs7.TimeStampToken;
  54.                 Console.WriteLine("TimeStamp service: " + ts.TimeStampInfo.Tsa);
  55.                 Console.WriteLine("Timestamp verified? " + pkcs7.VerifyTimestampImprint());
  56.             }
  57.             Console.WriteLine("Location: " + pkcs7.Location);
  58.             Console.WriteLine("Reason: " + pkcs7.Reason);
  59.             PdfDictionary sigDict = fields.GetSignatureDictionary(name);
  60.             PdfString contact = sigDict.GetAsString(PdfName.CONTACTINFO);
  61.             if (contact != null)
  62.                 Console.WriteLine("Contact info: " + contact);
  63.             perms = new SignaturePermissions(sigDict, perms);
  64.             Console.WriteLine("Signature type: " + (perms.Certification ? "certification" : "approval"));
  65.             Console.WriteLine("Filling out fields allowed: " + perms.FillInAllowed);
  66.             Console.WriteLine("Adding annotations allowed: " + perms.AnnotationsAllowed);
  67.             foreach (SignaturePermissions.FieldLock Lock in perms.FieldLocks) {
  68.                 Console.WriteLine("Lock: " + Lock);
  69.             }
  70.             return perms;
  71.         }
  72.        
  73.         public void InspectSignatures(String path) {
  74.             Console.WriteLine(path);
  75.             PdfReader reader = new PdfReader(path);
  76.             AcroFields fields = reader.AcroFields;
  77.             List names = fields.GetSignatureNames();
  78.             SignaturePermissions perms = null;
  79.             foreach (String name in names) {
  80.                 Console.WriteLine("===== " + name + " =====");
  81.                 perms = InspectSignature(fields, name, perms);
  82.             }
  83.             Console.WriteLine();
  84.         }
  85.        
  86.         static void Main(String[] args) {
  87.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  88.             C5_02_SignatureInfo app = new C5_02_SignatureInfo();
  89.             app.InspectSignatures(EXAMPLE1);
  90.             app.InspectSignatures(EXAMPLE2);
  91.             app.InspectSignatures(EXAMPLE3);
  92.             app.InspectSignatures(EXAMPLE4);
  93.             app.InspectSignatures(EXAMPLE5);
  94.             app.InspectSignatures(EXAMPLE6);
  95.         }
  96.     }
  97. }
C5_03_CertificateValidation.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using Org.BouncyCastle.Ocsp;
  13. using Org.BouncyCastle.Security.Certificates;
  14. using Org.BouncyCastle.X509;
  15. using iTextSharp.text.log;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18. using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
  19.  
  20. namespace signatures.chapter5 {
  21.     class C5_03_CertificateValidation : C5_01_SignatureIntegrity {
  22.         public const String ADOBE = "../../../../resources/adobeRootCA.cer";
  23.         public const String CACERT = "../../../../resources/CACertSigningAuthority.crt";
  24.         public const String BRUNO = "../../../../resources/bruno.crt";
  25.  
  26.         public const String EXAMPLE1 = "../../../../results/chapter3/hello_cacert_ocsp_ts.pdf";
  27.         public const String EXAMPLE2 = "../../../../results/chapter3/hello_token.pdf";
  28.         public const String EXAMPLE3 = "../../../../results/chapter2/hello_signed1.pdf";
  29.         public const String EXAMPLE4 = "../../../../results/chapter4/hello_smartcard_Signature.pdf";
  30.  
  31.         readonly private List certificates = new List();
  32.  
  33.         override public PdfPKCS7 VerifySignature(AcroFields fields, String name) {
  34.             PdfPKCS7 pkcs7 = base.VerifySignature(fields, name);
  35.             X509Certificate[] certs = pkcs7.SignCertificateChain;
  36.             DateTime cal = pkcs7.SignDate;
  37.            
  38.             Object[] errors = CertificateVerification.VerifyCertificates(certs, certificates, null, cal);
  39.             if (errors == null)
  40.                 Console.WriteLine("Certificates verified against the KeyStore");
  41.             else
  42.                 foreach (object error in errors)
  43.                     Console.WriteLine(error);
  44.             for (int i = 0; i < certs.Length; ++i) {
  45.                 X509Certificate cert = certs[i];
  46.                 Console.WriteLine("=== Certificate " + i + " ===");
  47.                 ShowCertificateInfo(cert, cal.ToLocalTime());
  48.             }
  49.             X509Certificate signCert = certs[0];
  50.             X509Certificate issuerCert = (certs.Length > 1 ? certs[1] : null);
  51.             Console.WriteLine("=== Checking validity of the document at the time of signing ===");
  52.             CheckRevocation(pkcs7, signCert, issuerCert, cal);
  53.             Console.WriteLine("=== Checking validity of the document today ===");
  54.             CheckRevocation(pkcs7, signCert, issuerCert, DateTime.Now);
  55.             return pkcs7;
  56.         }
  57.        
  58.         public static void CheckRevocation(PdfPKCS7 pkcs7, X509Certificate signCert, X509Certificate issuerCert, DateTime date) {
  59.             List ocsps = new List();
  60.             if (pkcs7.Ocsp != null)
  61.                 ocsps.Add(pkcs7.Ocsp);
  62.             OcspVerifier ocspVerifier = new OcspVerifier(null, ocsps);
  63.             List verification =
  64.                 ocspVerifier.Verify(signCert, issuerCert, date);
  65.             if (verification.Count == 0) {
  66.                 List crls = new List();
  67.                 if (pkcs7.CRLs != null)
  68.                     foreach (X509Crl crl in pkcs7.CRLs)
  69.                         crls.Add(crl);
  70.                 CrlVerifier crlVerifier = new CrlVerifier(null, crls);
  71.                 verification.AddRange(crlVerifier.Verify(signCert, issuerCert, date));
  72.             }
  73.             if (verification.Count == 0)
  74.                 Console.WriteLine("The signing certificate couldn't be verified");
  75.             else
  76.                 foreach (VerificationOK v in verification)
  77.                     Console.WriteLine(v);
  78.         }
  79.  
  80.         public void ShowCertificateInfo(X509Certificate cert, DateTime signDate) {
  81.             Console.WriteLine("Issuer: " + cert.IssuerDN);
  82.             Console.WriteLine("Subject: " + cert.SubjectDN);
  83.             Console.WriteLine("Valid from: " + cert.NotBefore.ToString("yyyy-MM-dd HH:mm:ss.ff"));
  84.             Console.WriteLine("Valid to: " + cert.NotAfter.ToString("yyyy-MM-dd HH:mm:ss.ff"));
  85.             try {
  86.                 cert.CheckValidity(signDate);
  87.                 Console.WriteLine("The certificate was valid at the time of signing.");
  88.             } catch (CertificateExpiredException e) {
  89.                 Console.WriteLine("The certificate was expired at the time of signing.");
  90.             } catch (CertificateNotYetValidException e) {
  91.                 Console.WriteLine("The certificate wasn't valid yet at the time of signing.");
  92.             }
  93.             try {
  94.                 cert.CheckValidity();
  95.                 Console.WriteLine("The certificate is still valid.");
  96.             } catch (CertificateExpiredException e) {
  97.                 Console.WriteLine("The certificate has expired.");
  98.             } catch (CertificateNotYetValidException e) {
  99.                 Console.WriteLine("The certificate isn't valid yet.");
  100.             }
  101.         }
  102.  
  103.         static void Main(String[] args) {
  104.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  105.             C5_03_CertificateValidation app = new C5_03_CertificateValidation();
  106.            
  107.             X509CertificateParser parser = new X509CertificateParser();
  108.             app.certificates.Add(parser.ReadCertificate(new FileStream(ADOBE, FileMode.Open)));
  109.             app.certificates.Add(parser.ReadCertificate(new FileStream(CACERT, FileMode.Open)));
  110.             app.certificates.Add(parser.ReadCertificate(new FileStream(BRUNO, FileMode.Open)));
  111.             app.VerifySignatures(EXAMPLE1);
  112.             app.VerifySignatures(EXAMPLE2);
  113.             app.VerifySignatures(EXAMPLE3);
  114.             app.VerifySignatures(EXAMPLE4);
  115.         }
  116.     }
  117. }
C5_04_LTV.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.util;
  13. using iTextSharp.text.log;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.security;
  16.  
  17. namespace signatures.chapter5 {
  18.     class C5_04_LTV {
  19.         public const String EXAMPLE1 = "../../../../results/chapter3/hello_token.pdf";
  20.         public const String EXAMPLE2 = "../../../../results/chapter4/hello_smartcard_Signature.pdf";
  21.         public const String EXAMPLE3 = "../../../../results/chapter3/hello_cacert_ocsp_ts.pdf";
  22.         public const String DEST = "../../../../results/chapter5/ltv_{0}.pdf";
  23.        
  24.         public static void Main(String[] args) {
  25.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  26.             Properties properties = new Properties();
  27.             properties.Load(new FileStream("c:/home/blowagie/key.properties", FileMode.Open));
  28.             String tsaUrl = properties["TSAURL"];
  29.             String tsaUser = properties["TSAUSERNAME"];
  30.             String tsaPass = properties["TSAPASSWORD"];
  31.             C5_04_LTV app = new C5_04_LTV();
  32.             ITSAClient tsa = new TSAClientBouncyCastle(tsaUrl, tsaUser, tsaPass, 6500, "SHA512");
  33.             IOcspClient ocsp = new OcspClientBouncyCastle();
  34.             app.AddLtv(EXAMPLE1, String.Format(DEST, 1), ocsp, new CrlClientOnline(), tsa);
  35.             Console.WriteLine();
  36.             app.AddLtv(EXAMPLE2, String.Format(DEST, 2), ocsp, new CrlClientOnline(), tsa);
  37.             Console.WriteLine();
  38.             app.AddLtv(EXAMPLE3, String.Format(DEST, 3), ocsp, new CrlClientOnline(), tsa);
  39.             Console.WriteLine();
  40.             app.AddLtv(String.Format(DEST, 1), String.Format(DEST, 4), null, new CrlClientOnline(), tsa);
  41.         }
  42.        
  43.         public void AddLtv(String src, String dest, IOcspClient ocsp, ICrlClient crl, ITSAClient tsa) {
  44.             PdfReader r = new PdfReader(src);
  45.             FileStream fos = new FileStream(dest, FileMode.Create);
  46.             PdfStamper stp = PdfStamper.CreateSignature(r, fos, '\0', null, true);
  47.             LtvVerification v = stp.LtvVerification;
  48.             AcroFields fields = stp.AcroFields;
  49.             List names = fields.GetSignatureNames();
  50.             String sigName = names[names.Count - 1];
  51.             PdfPKCS7 pkcs7 = fields.VerifySignature(sigName);
  52.             if (pkcs7.IsTsp)
  53.                 v.AddVerification(sigName, ocsp, crl, LtvVerification.CertificateOption.SIGNING_CERTIFICATE, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
  54.             else foreach (String name in names)
  55.                 v.AddVerification(name, ocsp, crl, LtvVerification.CertificateOption.WHOLE_CHAIN, LtvVerification.Level.OCSP_CRL, LtvVerification.CertificateInclusion.NO);
  56.             PdfSignatureAppearance sap = stp.SignatureAppearance;
  57.             LtvTimestamp.Timestamp(sap, tsa, null);
  58.         }
  59.     }
  60. }
C5_05_CheckLTV.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using Org.BouncyCastle.X509;
  12. using iTextSharp.text.log;
  13. using iTextSharp.text.pdf;
  14. using iTextSharp.text.pdf.security;
  15.  
  16. namespace signatures.chapter5 {
  17.     class C5_05_CheckLTV {
  18.         public const String EXAMPLE1 = "../../../../results/chapter5/ltv_1.pdf";
  19.         public const String EXAMPLE2 = "../../../../results/chapter5/ltv_2.pdf";
  20.         public const String EXAMPLE3 = "../../../../results/chapter5/ltv_3.pdf";
  21.         public const String EXAMPLE4 = "../../../../results/chapter5/ltv_4.pdf";
  22.  
  23.         public PdfPKCS7 VerifySignature(AcroFields fields, String name) {
  24.             Console.WriteLine("Signature covers whole document: " + fields.SignatureCoversWholeDocument(name));
  25.             Console.WriteLine("Document revision: " + fields.GetRevision(name) + " of " + fields.TotalRevisions);
  26.             PdfPKCS7 pkcs7 = fields.VerifySignature(name);
  27.             Console.WriteLine("Integrity check OK? " + pkcs7.Verify());
  28.             Console.WriteLine("Digest algorithm: " + pkcs7.GetHashAlgorithm());
  29.             Console.WriteLine("Encryption algorithm: " + pkcs7.GetEncryptionAlgorithm());
  30.             Console.WriteLine("Filter subtype: " + pkcs7.GetFilterSubtype());
  31.             X509Certificate cert = pkcs7.SigningCertificate;
  32.             Console.WriteLine("Name of the signer: " + CertificateInfo.GetSubjectFields(cert).GetField("CN"));
  33.             return pkcs7;
  34.         }
  35.        
  36.         public void VerifySignatures(String path) {
  37.             Console.WriteLine(path);
  38.             PdfReader reader = new PdfReader(path);
  39.             AcroFields fields = reader.AcroFields;
  40.             List names = fields.GetSignatureNames();
  41.             foreach (String name in names) {
  42.                 Console.WriteLine("===== " + name + " =====");
  43.                 VerifySignature(fields, name);
  44.             }
  45.             Console.WriteLine();
  46.         }
  47.        
  48.         public static void Main(String[] args) {
  49.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  50.             C5_05_CheckLTV app = new C5_05_CheckLTV();
  51.             app.VerifySignatures(EXAMPLE1);
  52.             app.VerifySignatures(EXAMPLE2);
  53.             app.VerifySignatures(EXAMPLE3);
  54.             app.VerifySignatures(EXAMPLE4);
  55.         }
  56.     }
  57. }
C5_06_ValidateLTV.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using Org.BouncyCastle.Security;
  13. using Org.BouncyCastle.X509;
  14. using iTextSharp.text.pdf;
  15. using iTextSharp.text.pdf.security;
  16.  
  17. namespace signatures.chapter5 {
  18.     class C5_06_ValidateLTV {
  19.         public const String ADOBE = "../../../../resources/adobeRootCA.cer";
  20.         public const String EXAMPLE1 = "../../../../results/chapter5/ltv_1.pdf";
  21.         public const String EXAMPLE2 = "../../../../results/chapter5/ltv_2.pdf";
  22.         public const String EXAMPLE3 = "../../../../results/chapter5/ltv_3.pdf";
  23.         public const String EXAMPLE4 = "../../../../results/chapter5/ltv_4.pdf";
  24.        
  25.         static void Main(String[] args) {
  26.             C5_06_ValidateLTV app = new C5_06_ValidateLTV();
  27.             Console.WriteLine(EXAMPLE1);
  28.             app.Validate(new PdfReader(EXAMPLE1));
  29.             Console.WriteLine();
  30.             Console.WriteLine(EXAMPLE2);
  31.             app.Validate(new PdfReader(EXAMPLE2));
  32.             Console.WriteLine();
  33.             Console.WriteLine(EXAMPLE3);
  34.             app.Validate(new PdfReader(EXAMPLE3));
  35.             Console.WriteLine();
  36.             Console.WriteLine(EXAMPLE4);
  37.             app.Validate(new PdfReader(EXAMPLE4));
  38.         }
  39.  
  40.         class MyVerifier : CertificateVerifier {
  41.             public MyVerifier(CertificateVerifier verifier) : base(verifier) {}
  42.  
  43.             override public List Verify(X509Certificate signCert, X509Certificate issuerCert, DateTime signDate) {
  44.                 Console.WriteLine(signCert.SubjectDN + ": ALL VERIFICATIONS DONE");
  45.                 return new List();
  46.             }
  47.         }
  48.        
  49.         public void Validate(PdfReader reader) {
  50.             List certificates = new List();
  51.             X509CertificateParser parser = new X509CertificateParser();
  52.             FileStream file = new FileStream(ADOBE, FileMode.Open);
  53.             certificates.Add(parser.ReadCertificate(file));
  54.            
  55.             MyVerifier custom = new MyVerifier(null);
  56.            
  57.             LtvVerifier data = new LtvVerifier(reader);
  58.             data.Certificates = certificates;
  59.             data.CertificateOption = LtvVerification.CertificateOption.WHOLE_CHAIN;
  60.             data.Verifier = custom;
  61.             data.OnlineCheckingAllowed = false;
  62.             data.VerifyRootCertificate = false;
  63.             List list = new List();
  64.             try {
  65.                 data.Verify(list);
  66.             }
  67.             catch (GeneralSecurityException e) {
  68.                 Console.WriteLine(e.ToString());
  69.             }
  70.             Console.WriteLine();
  71.             if (list.Count == 0)
  72.                 Console.WriteLine("The document can't be verified");
  73.             foreach (VerificationOK v in list)
  74.                 Console.WriteLine(v.ToString());
  75.             file.Close();
  76.         }
  77.     }
  78. }
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now