Digital signatures - chapter 2

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

1st November 2015
admin-marketing

Switch code for this example

C2_01_SignHelloWorld.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Rectangle;
  23. import com.itextpdf.text.pdf.PdfReader;
  24. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  25. import com.itextpdf.text.pdf.PdfStamper;
  26. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  27. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  28. import com.itextpdf.text.pdf.security.ExternalDigest;
  29. import com.itextpdf.text.pdf.security.ExternalSignature;
  30. import com.itextpdf.text.pdf.security.MakeSignature;
  31. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  32. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  33.  
  34. public class C2_01_SignHelloWorld {
  35.  
  36.     public static final String KEYSTORE = "src/main/resources/ks";
  37.     public static final char[] PASSWORD = "password".toCharArray();
  38.     public static final String SRC = "src/main/resources/hello.pdf";
  39.     public static final String DEST = "results/chapter2/hello_signed%s.pdf";
  40.    
  41.     public void sign(String src, String dest,
  42.             Certificate[] chain,
  43.             PrivateKey pk, String digestAlgorithm, String provider,
  44.             CryptoStandard subfilter,
  45.             String reason, String location)
  46.                     throws GeneralSecurityException, IOException, DocumentException {
  47.         // Creating the reader and the stamper
  48.         PdfReader reader = new PdfReader(src);
  49.         FileOutputStream os = new FileOutputStream(dest);
  50.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  51.         // Creating the appearance
  52.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  53.         appearance.setReason(reason);
  54.         appearance.setLocation(location);
  55.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  56.         // Creating the signature
  57.         ExternalDigest digest = new BouncyCastleDigest();
  58.         ExternalSignature signature = new PrivateKeySignature(pk, digestAlgorithm, provider);
  59.         MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, subfilter);
  60.     }
  61.    
  62.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  63.         BouncyCastleProvider provider = new BouncyCastleProvider();
  64.         Security.addProvider(provider);
  65.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  66.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  67.         String alias = (String)ks.aliases().nextElement();
  68.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  69.         Certificate[] chain = ks.getCertificateChain(alias);
  70.         C2_01_SignHelloWorld app = new C2_01_SignHelloWorld();
  71.         app.sign(SRC, String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Test 1", "Ghent");
  72.         app.sign(SRC, String.format(DEST, 2), chain, pk, DigestAlgorithms.SHA512, provider.getName(), CryptoStandard.CMS, "Test 2", "Ghent");
  73.         app.sign(SRC, String.format(DEST, 3), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CADES, "Test 3", "Ghent");
  74.         app.sign(SRC, String.format(DEST, 4), chain, pk, DigestAlgorithms.RIPEMD160, provider.getName(), CryptoStandard.CADES, "Test 4", "Ghent");
  75.     }
  76. }
C2_02_SignHelloWorldWithTempFile.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.File;
  11. import java.io.FileInputStream;
  12. import java.io.FileOutputStream;
  13. import java.io.IOException;
  14. import java.security.GeneralSecurityException;
  15. import java.security.KeyStore;
  16. import java.security.PrivateKey;
  17. import java.security.Security;
  18. import java.security.cert.Certificate;
  19.  
  20. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  21.  
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  26. import com.itextpdf.text.pdf.PdfStamper;
  27. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  28. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  29. import com.itextpdf.text.pdf.security.ExternalDigest;
  30. import com.itextpdf.text.pdf.security.ExternalSignature;
  31. import com.itextpdf.text.pdf.security.MakeSignature;
  32. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  33. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  34.  
  35. public class C2_02_SignHelloWorldWithTempFile {
  36.  
  37.     public static final String KEYSTORE = "src/main/resources/ks";
  38.     public static final char[] PASSWORD = "password".toCharArray();
  39.     public static final String SRC = "src/main/resources/hello.pdf";
  40.     public static final String TEMP = "results/chapter2/";
  41.     public static final String DEST = "results/chapter2/hello_signed_with_temp.pdf";
  42.    
  43.     public void sign(String src, String tmp, String dest,
  44.             Certificate[] chain, PrivateKey pk,
  45.             String digestAlgorithm,  String provider,
  46.             CryptoStandard subfilter,
  47.             String reason, String location)
  48.                     throws GeneralSecurityException, IOException, DocumentException {
  49.         // Creating the reader and the stamper
  50.         PdfReader reader = new PdfReader(src);
  51.         FileOutputStream os = new FileOutputStream(dest);
  52.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', new File(tmp));
  53.         // Creating the appearance
  54.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  55.         appearance.setReason(reason);
  56.         appearance.setLocation(location);
  57.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  58.         // Creating the signature
  59.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  60.         ExternalDigest digest = new BouncyCastleDigest();
  61.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  62.     }
  63.    
  64.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  65.         BouncyCastleProvider provider = new BouncyCastleProvider();
  66.         Security.addProvider(provider);
  67.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  68.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  69.         String alias = (String)ks.aliases().nextElement();
  70.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  71.         Certificate[] chain = ks.getCertificateChain(alias);
  72.         C2_02_SignHelloWorldWithTempFile app = new C2_02_SignHelloWorldWithTempFile();
  73.         app.sign(SRC, TEMP, DEST, chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Temp test", "Ghent");
  74.     }
  75. }
C2_03_SignEmptyField.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.pdf.PdfReader;
  23. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  24. import com.itextpdf.text.pdf.PdfStamper;
  25. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  26. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  27. import com.itextpdf.text.pdf.security.ExternalDigest;
  28. import com.itextpdf.text.pdf.security.ExternalSignature;
  29. import com.itextpdf.text.pdf.security.MakeSignature;
  30. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  31. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  32.  
  33. public class C2_03_SignEmptyField {
  34.  
  35.     public static final String KEYSTORE = "src/main/resources/ks";
  36.     public static final char[] PASSWORD = "password".toCharArray();
  37.     public static final String SRC = "src/main/resources/hello_to_sign.pdf";
  38.     public static final String DEST = "results/chapter2/field_signed%s.pdf";
  39.    
  40.     public void sign(String src, String name, String dest,
  41.             Certificate[] chain, PrivateKey pk,
  42.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  43.             String reason, String location)
  44.                     throws GeneralSecurityException, IOException, DocumentException {
  45.         // Creating the reader and the stamper
  46.         PdfReader reader = new PdfReader(src);
  47.         FileOutputStream os = new FileOutputStream(dest);
  48.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  49.         // Creating the appearance
  50.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  51.         appearance.setReason(reason);
  52.         appearance.setLocation(location);
  53.         appearance.setVisibleSignature(name);
  54.         // Creating the signature
  55.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  56.         ExternalDigest digest = new BouncyCastleDigest();
  57.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  58.     }
  59.    
  60.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  61.         BouncyCastleProvider provider = new BouncyCastleProvider();
  62.         Security.addProvider(provider);
  63.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  64.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  65.         String alias = (String)ks.aliases().nextElement();
  66.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  67.         Certificate[] chain = ks.getCertificateChain(alias);
  68.         C2_03_SignEmptyField app = new C2_03_SignEmptyField();
  69.         app.sign(SRC, "Signature1", String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Test 1", "Ghent");
  70.         app.sign(SRC, "Signature1", String.format(DEST, 2), chain, pk, DigestAlgorithms.SHA512, provider.getName(), CryptoStandard.CMS, "Test 2", "Ghent");
  71.         app.sign(SRC, "Signature1", String.format(DEST, 3), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CADES, "Test 3", "Ghent");
  72.         app.sign(SRC, "Signature1", String.format(DEST, 4), chain, pk, DigestAlgorithms.RIPEMD160, provider.getName(), CryptoStandard.CADES, "Test 4", "Ghent");
  73.     }
  74. }
C2_04_CreateEmptyField.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.BaseColor;
  22. import com.itextpdf.text.Document;
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.Element;
  25. import com.itextpdf.text.Paragraph;
  26. import com.itextpdf.text.Phrase;
  27. import com.itextpdf.text.Rectangle;
  28. import com.itextpdf.text.pdf.ColumnText;
  29. import com.itextpdf.text.pdf.PdfAnnotation;
  30. import com.itextpdf.text.pdf.PdfAppearance;
  31. import com.itextpdf.text.pdf.PdfFormField;
  32. import com.itextpdf.text.pdf.PdfReader;
  33. import com.itextpdf.text.pdf.PdfStamper;
  34. import com.itextpdf.text.pdf.PdfWriter;
  35. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  36. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  37.  
  38. public class C2_04_CreateEmptyField {
  39.  
  40.     public static final String KEYSTORE = "src/main/resources/ks";
  41.     public static final char[] PASSWORD = "password".toCharArray();
  42.     public static final String UNSIGNED = "results/chapter2/hello_empty.pdf";
  43.     public static final String SIGNAME = "Signature1";
  44.     public static final String DEST = "results/chapter2/field_signed.pdf";
  45.  
  46.     public static final String SRC = "src/main/resources/hello.pdf";
  47.     public static final String UNSIGNED2 = "results/chapter2/hello_empty2.pdf";
  48.    
  49.     public void createPdf(String filename) throws IOException, DocumentException {
  50.         // step 1: Create a Document
  51.         Document document = new Document();
  52.         // step 2: Create a PdfWriter
  53.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
  54.         // step 3: Open the Document
  55.         document.open();
  56.         // step 4: Add content
  57.         document.add(new Paragraph("Hello World!"));
  58.         // create a signature form field
  59.         PdfFormField field = PdfFormField.createSignature(writer);
  60.         field.setFieldName(SIGNAME);
  61.         // set the widget properties
  62.         field.setPage();
  63.         field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
  64.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  65.         // add it as an annotation
  66.         writer.addAnnotation(field);
  67.         // maybe you want to define an appearance
  68.         PdfAppearance tp = PdfAppearance.createAppearance(writer, 72, 48);
  69.         tp.setColorStroke(BaseColor.BLUE);
  70.         tp.setColorFill(BaseColor.LIGHT_GRAY);
  71.         tp.rectangle(0.5f, 0.5f, 71.5f, 47.5f);
  72.         tp.fillStroke();
  73.         tp.setColorFill(BaseColor.BLUE);
  74.         ColumnText.showTextAligned(tp, Element.ALIGN_CENTER, new Phrase("SIGN HERE"), 36, 24, 25);
  75.         field.setAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
  76.         // step 5: Close the Document
  77.         document.close();
  78.     }
  79.    
  80.     public void addField(String src, String dest) throws IOException, DocumentException {
  81.         PdfReader reader = new PdfReader(src);
  82.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  83.         // create a signature form field
  84.         PdfFormField field = PdfFormField.createSignature(stamper.getWriter());
  85.         field.setFieldName(SIGNAME);
  86.         // set the widget properties
  87.         field.setWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_OUTLINE);
  88.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  89.         // add the annotation
  90.         stamper.addAnnotation(field, 1);
  91.         // close the stamper
  92.         stamper.close();
  93.     }
  94.    
  95.     public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
  96.         C2_04_CreateEmptyField appCreate = new C2_04_CreateEmptyField();
  97.         appCreate.createPdf(UNSIGNED);
  98.         appCreate.addField(SRC, UNSIGNED2);
  99.  
  100.         BouncyCastleProvider provider = new BouncyCastleProvider();
  101.         Security.addProvider(provider);
  102.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  103.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  104.         String alias = (String)ks.aliases().nextElement();
  105.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  106.         Certificate[] chain = ks.getCertificateChain(alias);
  107.         C2_03_SignEmptyField appSign = new C2_03_SignEmptyField();
  108.         appSign.sign(UNSIGNED, SIGNAME, DEST, chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Test", "Ghent");
  109.     }
  110. }
C2_05_CustomAppearance.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.BaseColor;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Paragraph;
  24. import com.itextpdf.text.pdf.ColumnText;
  25. import com.itextpdf.text.pdf.PdfReader;
  26. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28. import com.itextpdf.text.pdf.PdfTemplate;
  29. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  30. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  31. import com.itextpdf.text.pdf.security.ExternalDigest;
  32. import com.itextpdf.text.pdf.security.ExternalSignature;
  33. import com.itextpdf.text.pdf.security.MakeSignature;
  34. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  35. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  36.  
  37. public class C2_05_CustomAppearance {
  38.  
  39.     public static final String KEYSTORE = "src/main/resources/ks";
  40.     public static final char[] PASSWORD = "password".toCharArray();
  41.     public static final String SRC = "src/main/resources/hello_to_sign.pdf";
  42.     public static final String DEST = "results/chapter2/signature_custom.pdf";
  43.    
  44.     public void sign(String src, String name, String dest,
  45.             Certificate[] chain, PrivateKey pk,
  46.             String digestAlgorithm, String provider,
  47.             CryptoStandard subfilter,
  48.             String reason, String location)
  49.                     throws GeneralSecurityException, IOException, DocumentException {
  50.         // Creating the reader and the stamper
  51.         PdfReader reader = new PdfReader(src);
  52.         FileOutputStream os = new FileOutputStream(dest);
  53.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  54.         // Creating the appearance
  55.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  56.         appearance.setReason(reason);
  57.         appearance.setLocation(location);
  58.         appearance.setVisibleSignature(name);
  59.         // Creating the appearance for layer 0
  60.         PdfTemplate n0 = appearance.getLayer(0);
  61.         float x = n0.getBoundingBox().getLeft();
  62.         float y = n0.getBoundingBox().getBottom();
  63.         float width = n0.getBoundingBox().getWidth();
  64.         float height = n0.getBoundingBox().getHeight();
  65.         n0.setColorFill(BaseColor.LIGHT_GRAY);
  66.         n0.rectangle(x, y, width, height);
  67.         n0.fill();
  68.         // Creating the appearance for layer 2
  69.         PdfTemplate n2 = appearance.getLayer(2);
  70.         ColumnText ct = new ColumnText(n2);
  71.         ct.setSimpleColumn(n2.getBoundingBox());
  72.         Paragraph p = new Paragraph("This document was signed by Bruno Specimen.");
  73.         ct.addElement(p);
  74.         ct.go();
  75.         // Creating the signature
  76.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  77.         ExternalDigest digest = new BouncyCastleDigest();
  78.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  79.     }
  80.    
  81.    
  82.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  83.         BouncyCastleProvider provider = new BouncyCastleProvider();
  84.         Security.addProvider(provider);
  85.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  86.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  87.         String alias = (String)ks.aliases().nextElement();
  88.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  89.         Certificate[] chain = ks.getCertificateChain(alias);
  90.         C2_05_CustomAppearance app = new C2_05_CustomAppearance();
  91.         app.sign(SRC, "Signature1", DEST, chain, pk,
  92.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  93.                 "Custom appearance example", "Ghent");
  94.     }
  95. }
C2_06_SignatureAppearance.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Font;
  23. import com.itextpdf.text.Image;
  24. import com.itextpdf.text.Font.FontFamily;
  25. import com.itextpdf.text.pdf.BaseFont;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  28. import com.itextpdf.text.pdf.PdfWriter;
  29. import com.itextpdf.text.pdf.PdfStamper;
  30. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  31. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  32. import com.itextpdf.text.pdf.security.ExternalDigest;
  33. import com.itextpdf.text.pdf.security.MakeSignature;
  34. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  35. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  36.  
  37. public class C2_06_SignatureAppearance {
  38.  
  39.     public static final String KEYSTORE = "src/main/resources/ks";
  40.     public static final char[] PASSWORD = "password".toCharArray();
  41.     public static final String IMG = "src/main/resources/1t3xt.gif";
  42.     public static final String SRC = "src/main/resources/hello_to_sign.pdf";
  43.     public static final String DEST = "results/chapter2/signature_appearance%s.pdf";
  44.  
  45.     public void sign1(String src, String name, String dest,
  46.             Certificate[] chain, PrivateKey pk,
  47.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  48.             String reason, String location)
  49.                     throws GeneralSecurityException, IOException, DocumentException {
  50.         // Creating the reader and the stamper
  51.         PdfReader reader = new PdfReader(src);
  52.         FileOutputStream os = new FileOutputStream(dest);
  53.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  54.         // Creating the appearance
  55.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  56.         appearance.setReason(reason);
  57.         appearance.setLocation(location);
  58.         appearance.setVisibleSignature(name);
  59.         // Custom text and custom font
  60.         appearance.setLayer2Text("This document was signed by Bruno Specimen");
  61.         appearance.setLayer2Font(new Font(FontFamily.TIMES_ROMAN));
  62.         // Creating the signature
  63.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  64.         ExternalDigest digest = new BouncyCastleDigest();
  65.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  66.     }
  67.    
  68.     public void sign2(String src, String name, String dest,
  69.             Certificate[] chain, PrivateKey pk,
  70.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  71.             String reason, String location)
  72.                     throws GeneralSecurityException, IOException, DocumentException {
  73.         // Creating the reader and the stamper
  74.         PdfReader reader = new PdfReader(src);
  75.         FileOutputStream os = new FileOutputStream(dest);
  76.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  77.         // Creating the appearance
  78.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  79.         appearance.setReason(reason);
  80.         appearance.setLocation(location);
  81.         appearance.setVisibleSignature(name);
  82.         // Custom text, custom font, and right-to-left writing
  83.         appearance.setLayer2Text("\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628");
  84.         appearance.setRunDirection(PdfWriter.RUN_DIRECTION_RTL);
  85.         appearance.setLayer2Font(new Font(BaseFont.createFont("C:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 12));
  86.         // Creating the signature
  87.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  88.         ExternalDigest digest = new BouncyCastleDigest();
  89.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  90.     }
  91.    
  92.     public void sign3(String src, String name, String dest,
  93.             Certificate[] chain, PrivateKey pk,
  94.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  95.             String reason, String location)
  96.                     throws GeneralSecurityException, IOException, DocumentException {
  97.         // Creating the reader and the stamper
  98.         PdfReader reader = new PdfReader(src);
  99.         FileOutputStream os = new FileOutputStream(dest);
  100.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  101.         // Creating the appearance
  102.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  103.         appearance.setReason(reason);
  104.         appearance.setLocation(location);
  105.         appearance.setVisibleSignature(name);
  106.         // Custom text and background image
  107.         appearance.setLayer2Text("This document was signed by Bruno Specimen");
  108.         appearance.setImage(Image.getInstance(IMG));
  109.         appearance.setImageScale(1);
  110.         // Creating the signature
  111.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  112.         ExternalDigest digest = new BouncyCastleDigest();
  113.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  114.     }
  115.    
  116.     public void sign4(String src, String name, String dest,
  117.             Certificate[] chain, PrivateKey pk,
  118.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  119.             String reason, String location)
  120.                     throws GeneralSecurityException, IOException, DocumentException {
  121.         // Creating the reader and the stamper
  122.         PdfReader reader = new PdfReader(src);
  123.         FileOutputStream os = new FileOutputStream(dest);
  124.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  125.         // Creating the appearance
  126.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  127.         appearance.setReason(reason);
  128.         appearance.setLocation(location);
  129.         appearance.setVisibleSignature(name);
  130.         // Default text and scaled background image
  131.         appearance.setImage(Image.getInstance(IMG));
  132.         appearance.setImageScale(-1);
  133.         // Creating the signature
  134.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  135.         ExternalDigest digest = new BouncyCastleDigest();
  136.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  137.     }
  138.    
  139.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  140.         BouncyCastleProvider provider = new BouncyCastleProvider();
  141.         Security.addProvider(provider);
  142.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  143.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  144.         String alias = (String)ks.aliases().nextElement();
  145.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  146.         Certificate[] chain = ks.getCertificateChain(alias);
  147.         C2_06_SignatureAppearance app = new C2_06_SignatureAppearance();
  148.         app.sign1(SRC, "Signature1", String.format(DEST, 1), chain, pk,
  149.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  150.                 "Custom appearance example", "Ghent");
  151.         app.sign2(SRC, "Signature1", String.format(DEST, 2), chain, pk,
  152.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  153.                 "Custom appearance example", "Ghent");
  154.         app.sign3(SRC, "Signature1", String.format(DEST, 3), chain, pk,
  155.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  156.                 "Custom appearance example", "Ghent");
  157.         app.sign4(SRC, "Signature1", String.format(DEST, 4), chain, pk,
  158.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  159.                 "Custom appearance example", "Ghent");
  160.     }
  161. }
C2_07_SignatureAppearances.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18. import java.util.Date;
  19.  
  20. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  21.  
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Image;
  24. import com.itextpdf.text.pdf.PdfReader;
  25. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  26. import com.itextpdf.text.pdf.PdfSignatureAppearance.RenderingMode;
  27. import com.itextpdf.text.pdf.PdfStamper;
  28. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  29. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  30. import com.itextpdf.text.pdf.security.ExternalDigest;
  31. import com.itextpdf.text.pdf.security.MakeSignature;
  32. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  33. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  34.  
  35. public class C2_07_SignatureAppearances {
  36.  
  37.     public static final String KEYSTORE = "src/main/resources/ks";
  38.     public static final char[] PASSWORD = "password".toCharArray();
  39.     public static final String IMG = "src/main/resources/1t3xt.gif";
  40.     public static final String SRC = "src/main/resources/hello_to_sign.pdf";
  41.     public static final String DEST = "results/chapter2/signature_appearance_%s.pdf";
  42.    
  43.     public void sign(String src, String name, String dest,
  44.             Certificate[] chain, PrivateKey pk,
  45.             String digestAlgorithm, String provider,
  46.             CryptoStandard subfilter,
  47.             String reason, String location, RenderingMode renderingMode,
  48.             Image image)
  49.                     throws GeneralSecurityException, IOException, DocumentException {
  50.         // Creating the reader and the stamper
  51.         PdfReader reader = new PdfReader(src);
  52.         FileOutputStream os = new FileOutputStream(dest);
  53.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  54.         // Creating the appearance
  55.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  56.         appearance.setReason(reason);
  57.         appearance.setLocation(location);
  58.         appearance.setVisibleSignature(name);
  59.         appearance.setLayer2Text("Signed on " + new Date().toString());
  60.         appearance.setRenderingMode(renderingMode);
  61.         appearance.setSignatureGraphic(image);
  62.         // Creating the signature
  63.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  64.         ExternalDigest digest = new BouncyCastleDigest();
  65.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  66.     }
  67.    
  68.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  69.         BouncyCastleProvider provider = new BouncyCastleProvider();
  70.         Security.addProvider(provider);
  71.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  72.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  73.         String alias = (String)ks.aliases().nextElement();
  74.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  75.         Certificate[] chain = ks.getCertificateChain(alias);
  76.         Image image = Image.getInstance(IMG);
  77.         C2_07_SignatureAppearances app = new C2_07_SignatureAppearances();
  78.         app.sign(SRC, "Signature1", String.format(DEST, 1), chain, pk,
  79.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  80.                 "Appearance 1", "Ghent", RenderingMode.DESCRIPTION, null);
  81.         app.sign(SRC, "Signature1", String.format(DEST, 2), chain, pk,
  82.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  83.                 "Appearance 2", "Ghent", RenderingMode.NAME_AND_DESCRIPTION, null);
  84.         app.sign(SRC, "Signature1", String.format(DEST, 3), chain, pk,
  85.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  86.                 "Appearance 3", "Ghent", RenderingMode.GRAPHIC_AND_DESCRIPTION, image);
  87.         app.sign(SRC, "Signature1", String.format(DEST, 4), chain, pk,
  88.                 DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS,
  89.                 "Appearance 4", "Ghent", RenderingMode.GRAPHIC, image);
  90.     }
  91. }
C2_08_SignatureMetadata.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18. import java.util.Calendar;
  19. import java.util.GregorianCalendar;
  20.  
  21. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  22.  
  23. import com.itextpdf.text.DocumentException;
  24. import com.itextpdf.text.pdf.PdfDictionary;
  25. import com.itextpdf.text.pdf.PdfName;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  28. import com.itextpdf.text.pdf.PdfSignatureAppearance.SignatureEvent;
  29. import com.itextpdf.text.pdf.PdfStamper;
  30. import com.itextpdf.text.pdf.PdfString;
  31. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  32. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  33. import com.itextpdf.text.pdf.security.ExternalDigest;
  34. import com.itextpdf.text.pdf.security.MakeSignature;
  35. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  36. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  37.  
  38. public class C2_08_SignatureMetadata {
  39.  
  40.     public static final String KEYSTORE = "src/main/resources/ks";
  41.     public static final char[] PASSWORD = "password".toCharArray();
  42.     public static final String SRC = "src/main/resources/hello_to_sign.pdf";
  43.     public static final String DEST = "results/chapter2/field_metadata.pdf";
  44.    
  45.     public void sign(String src, String name, String dest,
  46.             Certificate[] chain, PrivateKey pk,
  47.             String digestAlgorithm, String provider,
  48.             CryptoStandard subfilter,
  49.             String reason, String location, String contact, Calendar signDate,
  50.             final String fullName)
  51.                     throws GeneralSecurityException, IOException, DocumentException {
  52.         // Creating the reader and the stamper
  53.         PdfReader reader = new PdfReader(src);
  54.         FileOutputStream os = new FileOutputStream(dest);
  55.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  56.         // Creating the appearance
  57.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  58.         appearance.setReason(reason);
  59.         appearance.setLocation(location);
  60.         appearance.setVisibleSignature(name);
  61.         appearance.setContact(contact);
  62.         appearance.setSignDate(signDate);
  63.         appearance.setSignatureEvent(
  64.             new SignatureEvent(){
  65.                 public void getSignatureDictionary(PdfDictionary sig) {
  66.                     sig.put(PdfName.NAME, new PdfString(fullName));
  67.                 }
  68.             }
  69.         );
  70.         // Creating the signature
  71.         PrivateKeySignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  72.         ExternalDigest digest = new BouncyCastleDigest();
  73.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  74.     }
  75.    
  76.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  77.         BouncyCastleProvider provider = new BouncyCastleProvider();
  78.         Security.addProvider(provider);
  79.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  80.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  81.         String alias = (String)ks.aliases().nextElement();
  82.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  83.         Certificate[] chain = ks.getCertificateChain(alias);
  84.         C2_08_SignatureMetadata app = new C2_08_SignatureMetadata();
  85.         app.sign(SRC, "Signature1", String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Test metadata", "Ghent", "555 123 456", new GregorianCalendar(2012, GregorianCalendar.AUGUST, 5), "Bruno L. Specimen");
  86.     }
  87. }
C2_09_SignatureTypes.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.DocumentException;
  22. import com.itextpdf.text.Element;
  23. import com.itextpdf.text.Phrase;
  24. import com.itextpdf.text.Rectangle;
  25. import com.itextpdf.text.pdf.ColumnText;
  26. import com.itextpdf.text.pdf.PdfAnnotation;
  27. import com.itextpdf.text.pdf.PdfReader;
  28. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  29. import com.itextpdf.text.pdf.PdfStamper;
  30. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  31. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  32. import com.itextpdf.text.pdf.security.ExternalDigest;
  33. import com.itextpdf.text.pdf.security.ExternalSignature;
  34. import com.itextpdf.text.pdf.security.MakeSignature;
  35. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  36. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  37.  
  38. public class C2_09_SignatureTypes {
  39.  
  40.     public static final String KEYSTORE = "src/main/resources/ks";
  41.     public static final char[] PASSWORD = "password".toCharArray();
  42.     public static final String SRC = "src/main/resources/hello.pdf";
  43.     public static final String DEST = "results/chapter2/hello_level_%s.pdf";
  44.    
  45.     public void sign(String src, String dest,
  46.             Certificate[] chain, PrivateKey pk,
  47.             String digestAlgorithm, String provider,
  48.             CryptoStandard subfilter, int certificationLevel,
  49.             String reason, String location)
  50.                     throws GeneralSecurityException, IOException, DocumentException {
  51.         // Creating the reader and the stamper
  52.         PdfReader reader = new PdfReader(src);
  53.         FileOutputStream os = new FileOutputStream(dest);
  54.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  55.         // Creating the appearance
  56.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  57.         appearance.setReason(reason);
  58.         appearance.setLocation(location);
  59.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  60.         appearance.setCertificationLevel(certificationLevel);
  61.         // Creating the signature
  62.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  63.         ExternalDigest digest = new BouncyCastleDigest();
  64.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  65.     }
  66.    
  67.     public void addText(String src, String dest) throws IOException, DocumentException {
  68.         PdfReader reader = new PdfReader(src);
  69.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
  70.         ColumnText.showTextAligned(stamper.getOverContent(1), Element.ALIGN_LEFT, new Phrase("TOP SECRET"), 36, 820, 0);
  71.         stamper.close();
  72.     }
  73.    
  74.     public void addAnnotation(String src, String dest) throws IOException, DocumentException {
  75.         PdfReader reader = new PdfReader(src);
  76.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
  77.         PdfAnnotation comment = PdfAnnotation.createText(stamper.getWriter(),
  78.                 new Rectangle(200, 800, 250, 820), "Finally Signed!",
  79.                 "Bruno Specimen has finally signed the document", true, "Comment");
  80.         stamper.addAnnotation(comment, 1);
  81.         stamper.close();
  82.     }
  83.    
  84.     public void addWrongAnnotation(String src, String dest) throws IOException, DocumentException {
  85.         PdfReader reader = new PdfReader(src);
  86.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
  87.         PdfAnnotation comment = PdfAnnotation.createText(stamper.getWriter(),
  88.                 new Rectangle(200, 800, 250, 820), "Finally Signed!",
  89.                 "Bruno Specimen has finally signed the document", true, "Comment");
  90.         stamper.addAnnotation(comment, 1);
  91.         stamper.close();
  92.     }
  93.    
  94.     public void signAgain(String src, String dest, Certificate[] chain, PrivateKey pk,
  95.             String digestAlgorithm, String provider,
  96.             CryptoStandard subfilter,
  97.             String reason, String location)
  98.                     throws GeneralSecurityException, IOException, DocumentException {
  99.         // Creating the reader and the stamper
  100.         PdfReader reader = new PdfReader(src);
  101.         FileOutputStream os = new FileOutputStream(dest);
  102.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  103.         // Creating the appearance
  104.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  105.         appearance.setReason(reason);
  106.         appearance.setLocation(location);
  107.         appearance.setVisibleSignature(new Rectangle(36, 700, 144, 732), 1, "Signature2");
  108.         // Creating the signature
  109.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  110.         ExternalDigest digest = new BouncyCastleDigest();
  111.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, subfilter);
  112.     }
  113.    
  114.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  115.         BouncyCastleProvider provider = new BouncyCastleProvider();
  116.         Security.addProvider(provider);
  117.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  118.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  119.         String alias = (String)ks.aliases().nextElement();
  120.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  121.         Certificate[] chain = ks.getCertificateChain(alias);
  122.         C2_09_SignatureTypes app = new C2_09_SignatureTypes();
  123.         app.sign(SRC, String.format(DEST, 1), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, PdfSignatureAppearance.NOT_CERTIFIED, "Test 1", "Ghent");
  124.         app.sign(SRC, String.format(DEST, 2), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent");
  125.         app.sign(SRC, String.format(DEST, 3), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, "Test 1", "Ghent");
  126.         app.sign(SRC, String.format(DEST, 4), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent");
  127.         app.addWrongAnnotation(String.format(DEST, 1), String.format(DEST, "1_annotated_wrong"));
  128.         app.addAnnotation(String.format(DEST, 1), String.format(DEST, "1_annotated"));
  129.         app.addAnnotation(String.format(DEST, 2), String.format(DEST, "2_annotated"));
  130.         app.addAnnotation(String.format(DEST, 3), String.format(DEST, "3_annotated"));
  131.         app.addAnnotation(String.format(DEST, 4), String.format(DEST, "4_annotated"));
  132.         app.addText(String.format(DEST, 1), String.format(DEST, "1_text"));
  133.         app.signAgain(String.format(DEST, 1), String.format(DEST, "1_double"), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Second signature test", "Gent");
  134.         app.signAgain(String.format(DEST, 2), String.format(DEST, "2_double"), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Second signature test", "Gent");
  135.         app.signAgain(String.format(DEST, 3), String.format(DEST, "3_double"), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Second signature test", "Gent");
  136.         app.signAgain(String.format(DEST, 4), String.format(DEST, "4_double"), chain, pk, DigestAlgorithms.SHA256, provider.getName(), CryptoStandard.CMS, "Second signature test", "Gent");
  137.     }
  138. }
C2_10_SequentialSignatures.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.pdf.PdfAnnotation;
  25. import com.itextpdf.text.pdf.PdfContentByte;
  26. import com.itextpdf.text.pdf.PdfFormField;
  27. import com.itextpdf.text.pdf.PdfPCell;
  28. import com.itextpdf.text.pdf.PdfPCellEvent;
  29. import com.itextpdf.text.pdf.PdfPTable;
  30. import com.itextpdf.text.pdf.PdfReader;
  31. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  32. import com.itextpdf.text.pdf.PdfStamper;
  33. import com.itextpdf.text.pdf.PdfWriter;
  34. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  35. import com.itextpdf.text.pdf.security.ExternalDigest;
  36. import com.itextpdf.text.pdf.security.ExternalSignature;
  37. import com.itextpdf.text.pdf.security.MakeSignature;
  38. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  39. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  40.  
  41. public class C2_10_SequentialSignatures {
  42.     public static final String FORM = "results/chapter2/multiple_signatures.pdf";
  43.     public static final String ALICE = "src/main/resources/alice";
  44.     public static final String BOB = "src/main/resources/bob";
  45.     public static final String CAROL = "src/main/resources/carol";
  46.     public static final char[] PASSWORD = "password".toCharArray();
  47.     public static final String DEST = "results/chapter2/signed_by_%s.pdf";
  48.    
  49.     public void createForm() throws IOException, DocumentException {
  50.         Document document = new Document();
  51.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FORM));
  52.         document.open();
  53.         PdfPTable table = new PdfPTable(1);
  54.         table.setWidthPercentage(100);
  55.         table.addCell("Signer 1: Alice");
  56.         table.addCell(createSignatureFieldCell(writer, "sig1"));
  57.         table.addCell("Signer 2: Bob");
  58.         table.addCell(createSignatureFieldCell(writer, "sig2"));
  59.         table.addCell("Signer 3: Carol");
  60.         table.addCell(createSignatureFieldCell(writer, "sig3"));
  61.         document.add(table);
  62.         document.close();
  63.     }
  64.    
  65.     protected PdfPCell createSignatureFieldCell(PdfWriter writer, String name) {
  66.         PdfPCell cell = new PdfPCell();
  67.         cell.setMinimumHeight(50);
  68.         PdfFormField field = PdfFormField.createSignature(writer);
  69.         field.setFieldName(name);
  70.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  71.         cell.setCellEvent(new MySignatureFieldEvent(field));
  72.         return cell;
  73.     }
  74.    
  75.     public class MySignatureFieldEvent implements PdfPCellEvent {
  76.  
  77.         public PdfFormField field;
  78.        
  79.         public MySignatureFieldEvent(PdfFormField field) {
  80.             this.field = field;
  81.         }
  82.        
  83.         public void cellLayout(PdfPCell cell, Rectangle position,
  84.                 PdfContentByte[] canvases) {
  85.             PdfWriter writer = canvases[0].getPdfWriter();
  86.             field.setPage();
  87.             field.setWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  88.             writer.addAnnotation(field);
  89.         }
  90.        
  91.     }
  92.    
  93.     public void sign(String keystore, int level,
  94.             String src, String name, String dest)
  95.                     throws GeneralSecurityException, IOException, DocumentException {
  96.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  97.         ks.load(new FileInputStream(keystore), PASSWORD);
  98.         String alias = (String)ks.aliases().nextElement();
  99.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  100.         Certificate[] chain = ks.getCertificateChain(alias);
  101.         // Creating the reader and the stamper
  102.         PdfReader reader = new PdfReader(src);
  103.         FileOutputStream os = new FileOutputStream(dest);
  104.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  105.         // Creating the appearance
  106.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  107.         appearance.setVisibleSignature(name);
  108.         appearance.setCertificationLevel(level);
  109.         // Creating the signature
  110.         ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
  111.         ExternalDigest digest = new BouncyCastleDigest();
  112.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  113.     }
  114.    
  115.     public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
  116.         BouncyCastleProvider provider = new BouncyCastleProvider();
  117.         Security.addProvider(provider);
  118.         C2_10_SequentialSignatures app = new C2_10_SequentialSignatures();
  119.         app.createForm();
  120.        
  121.         app.sign(ALICE, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, FORM, "sig1", String.format(DEST, "alice"));
  122.         app.sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.format(DEST, "alice"), "sig2", String.format(DEST, "bob"));
  123.         app.sign(CAROL, PdfSignatureAppearance.NOT_CERTIFIED, String.format(DEST, "bob"), "sig3", String.format(DEST, "carol"));
  124.  
  125.         app.sign(ALICE, PdfSignatureAppearance.NOT_CERTIFIED, FORM, "sig1", String.format(DEST, "alice2"));
  126.         app.sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.format(DEST, "alice2"), "sig2", String.format(DEST, "bob2"));
  127.         app.sign(CAROL, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, String.format(DEST, "bob2"), "sig3", String.format(DEST, "carol2"));
  128.  
  129.         app.sign(ALICE, PdfSignatureAppearance.NOT_CERTIFIED, FORM, "sig1", String.format(DEST, "alice3"));
  130.         app.sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.format(DEST, "alice3"), "sig2", String.format(DEST, "bob3"));
  131.         app.sign(CAROL, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, String.format(DEST, "bob3"), "sig3", String.format(DEST, "carol3"));
  132.        
  133.         app.sign(ALICE, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, FORM, "sig1", String.format(DEST, "alice4"));
  134.         app.sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.format(DEST, "alice4"), "sig2", String.format(DEST, "bob4"));
  135.         app.sign(CAROL, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, String.format(DEST, "bob4"), "sig3", String.format(DEST, "carol4"));
  136.     }
  137. }
C2_11_SignatureWorkflow.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.ExceptionConverter;
  24. import com.itextpdf.text.Rectangle;
  25. import com.itextpdf.text.pdf.AcroFields;
  26. import com.itextpdf.text.pdf.PdfAnnotation;
  27. import com.itextpdf.text.pdf.PdfContentByte;
  28. import com.itextpdf.text.pdf.PdfFormField;
  29. import com.itextpdf.text.pdf.PdfPCell;
  30. import com.itextpdf.text.pdf.PdfPCellEvent;
  31. import com.itextpdf.text.pdf.PdfPTable;
  32. import com.itextpdf.text.pdf.PdfReader;
  33. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  34. import com.itextpdf.text.pdf.PdfStamper;
  35. import com.itextpdf.text.pdf.PdfWriter;
  36. import com.itextpdf.text.pdf.TextField;
  37. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  38. import com.itextpdf.text.pdf.security.ExternalDigest;
  39. import com.itextpdf.text.pdf.security.ExternalSignature;
  40. import com.itextpdf.text.pdf.security.MakeSignature;
  41. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  42. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  43.  
  44. public class C2_11_SignatureWorkflow {
  45.     public static final String FORM = "results/chapter2/form.pdf";
  46.     public static final String ALICE = "src/main/resources/alice";
  47.     public static final String BOB = "src/main/resources/bob";
  48.     public static final String CAROL = "src/main/resources/carol";
  49.     public static final String DAVE = "src/main/resources/dave";
  50.     public static final char[] PASSWORD = "password".toCharArray();
  51.     public static final String DEST = "results/chapter2/step%s_signed_by_%s.pdf";
  52.    
  53.     public class MyTextFieldEvent implements PdfPCellEvent {
  54.  
  55.         public String name;
  56.        
  57.         public MyTextFieldEvent(String name) {
  58.             this.name = name;
  59.         }
  60.  
  61.         public void cellLayout(PdfPCell cell, Rectangle position,
  62.                 PdfContentByte[] canvases) {
  63.             PdfWriter writer = canvases[0].getPdfWriter();
  64.             TextField text = new TextField(writer, position, name);
  65.             try {
  66.                 writer.addAnnotation(text.getTextField());
  67.             } catch (IOException e) {
  68.                 throw new ExceptionConverter(e);
  69.             } catch (DocumentException e) {
  70.                 throw new ExceptionConverter(e);
  71.             }
  72.         }
  73.     }
  74.    
  75.     public class MySignatureFieldEvent implements PdfPCellEvent {
  76.  
  77.         public PdfFormField field;
  78.        
  79.         public MySignatureFieldEvent(PdfFormField field) {
  80.             this.field = field;
  81.         }
  82.        
  83.         public void cellLayout(PdfPCell cell, Rectangle position,
  84.                 PdfContentByte[] canvases) {
  85.             PdfWriter writer = canvases[0].getPdfWriter();
  86.             field.setPage();
  87.             field.setWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  88.             writer.addAnnotation(field);
  89.         }
  90.        
  91.     }
  92.    
  93.     public void createForm() throws IOException, DocumentException {
  94.         Document document = new Document();
  95.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FORM));
  96.         document.open();
  97.         PdfPTable table = new PdfPTable(1);
  98.         table.setWidthPercentage(100);
  99.         table.addCell("Written by Alice");
  100.         table.addCell(createSignatureFieldCell(writer, "sig1"));
  101.         table.addCell("For approval by Bob");
  102.         table.addCell(createTextFieldCell("approved_bob"));
  103.         table.addCell(createSignatureFieldCell(writer, "sig2"));
  104.         table.addCell("For approval by Carol");
  105.         table.addCell(createTextFieldCell("approved_carol"));
  106.         table.addCell(createSignatureFieldCell(writer, "sig3"));
  107.         table.addCell("For approval by Dave");
  108.         table.addCell(createTextFieldCell("approved_dave"));
  109.         table.addCell(createSignatureFieldCell(writer, "sig4"));
  110.         document.add(table);
  111.         document.close();
  112.     }
  113.    
  114.     protected PdfPCell createTextFieldCell(String name) {
  115.         PdfPCell cell = new PdfPCell();
  116.         cell.setMinimumHeight(20);
  117.         cell.setCellEvent(new MyTextFieldEvent(name));
  118.         return cell;
  119.     }
  120.    
  121.     protected PdfPCell createSignatureFieldCell(PdfWriter writer, String name) {
  122.         PdfPCell cell = new PdfPCell();
  123.         cell.setMinimumHeight(50);
  124.         PdfFormField field = PdfFormField.createSignature(writer);
  125.         field.setFieldName(name);
  126.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  127.         cell.setCellEvent(new MySignatureFieldEvent(field));
  128.         return cell;
  129.     }
  130.    
  131.     public void certify(String keystore,
  132.             String src, String name, String dest)
  133.                     throws GeneralSecurityException, IOException, DocumentException {
  134.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  135.         ks.load(new FileInputStream(keystore), PASSWORD);
  136.         String alias = (String)ks.aliases().nextElement();
  137.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  138.         Certificate[] chain = ks.getCertificateChain(alias);
  139.         // Creating the reader and the stamper
  140.         PdfReader reader = new PdfReader(src);
  141.         FileOutputStream os = new FileOutputStream(dest);
  142.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  143.         // Creating the appearance
  144.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  145.         appearance.setVisibleSignature(name);
  146.         appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING);
  147.         // Creating the signature
  148.         ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
  149.         ExternalDigest digest = new BouncyCastleDigest();
  150.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  151.     }
  152.    
  153.     public void fillOut(String src, String dest, String name, String value) throws IOException, DocumentException {
  154.         PdfReader reader = new PdfReader(src);
  155.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
  156.         AcroFields form = stamper.getAcroFields();
  157.         form.setField(name, value);
  158.         form.setFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  159.         stamper.close();
  160.     }
  161.    
  162.     public void sign(String keystore,
  163.             String src, String name, String dest)
  164.                     throws GeneralSecurityException, IOException, DocumentException {
  165.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  166.         ks.load(new FileInputStream(keystore), PASSWORD);
  167.         String alias = (String)ks.aliases().nextElement();
  168.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  169.         Certificate[] chain = ks.getCertificateChain(alias);
  170.         // Creating the reader and the stamper
  171.         PdfReader reader = new PdfReader(src);
  172.         FileOutputStream os = new FileOutputStream(dest);
  173.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  174.         // Creating the appearance
  175.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  176.         appearance.setVisibleSignature(name);
  177.         // Creating the signature
  178.         ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
  179.         ExternalDigest digest = new BouncyCastleDigest();
  180.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  181.     }
  182.    
  183.     public void fillOutAndSign(String keystore,
  184.             String src, String name, String fname, String value, String dest)
  185.                     throws GeneralSecurityException, IOException, DocumentException {
  186.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  187.         ks.load(new FileInputStream(keystore), PASSWORD);
  188.         String alias = (String)ks.aliases().nextElement();
  189.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  190.         Certificate[] chain = ks.getCertificateChain(alias);
  191.         // Creating the reader and the stamper
  192.         PdfReader reader = new PdfReader(src);
  193.         FileOutputStream os = new FileOutputStream(dest);
  194.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  195.         AcroFields form = stamper.getAcroFields();
  196.         form.setField(fname, value);
  197.         form.setFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
  198.         // Creating the appearance
  199.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  200.         appearance.setVisibleSignature(name);
  201.         // Creating the signature
  202.         ExternalSignature pks = new PrivateKeySignature(pk, "SHA-256", "BC");
  203.         ExternalDigest digest = new BouncyCastleDigest();
  204.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  205.     }
  206.    
  207.     public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
  208.         BouncyCastleProvider provider = new BouncyCastleProvider();
  209.         Security.addProvider(provider);
  210.         C2_11_SignatureWorkflow app = new C2_11_SignatureWorkflow();
  211.         app.createForm();
  212.         app.certify(ALICE, FORM, "sig1", String.format(DEST, 1, "alice"));
  213.         app.fillOut(String.format(DEST, 1, "alice"), String.format(DEST, 2, "alice_and_filled_out_by_bob"), "approved_bob", "Read and Approved by Bob");
  214.         app.sign(BOB, String.format(DEST, 2, "alice_and_filled_out_by_bob"), "sig2", String.format(DEST, 3, "alice_and_bob"));
  215.         app.fillOut(String.format(DEST, 3, "alice_and_bob"), String.format(DEST, 4, "alice_and_bob_filled_out_by_carol"), "approved_carol", "Read and Approved by Carol");
  216.         app.sign(CAROL, String.format(DEST, 4, "alice_and_bob_filled_out_by_carol"), "sig3", String.format(DEST, 5, "alice_bob_and_carol"));
  217.         app.fillOutAndSign(DAVE, String.format(DEST, 5, "alice_bob_and_carol"), "sig4", "approved_dave", "Read and Approved by Dave", String.format(DEST, 6, "alice_bob_carol_and_dave"));
  218.     }
  219. }
C2_12_LockFields.java
  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. package signatures.chapter2;
  9.  
  10. import java.io.FileInputStream;
  11. import java.io.FileOutputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18.  
  19. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  20.  
  21. import com.itextpdf.text.Document;
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.ExceptionConverter;
  24. import com.itextpdf.text.Rectangle;
  25. import com.itextpdf.text.pdf.AcroFields;
  26. import com.itextpdf.text.pdf.PdfAnnotation;
  27. import com.itextpdf.text.pdf.PdfContentByte;
  28. import com.itextpdf.text.pdf.PdfDictionary;
  29. import com.itextpdf.text.pdf.PdfFormField;
  30. import com.itextpdf.text.pdf.PdfName;
  31. import com.itextpdf.text.pdf.PdfPCell;
  32. import com.itextpdf.text.pdf.PdfPCellEvent;
  33. import com.itextpdf.text.pdf.PdfPTable;
  34. import com.itextpdf.text.pdf.PdfReader;
  35. import com.itextpdf.text.pdf.PdfSigLockDictionary;
  36. import com.itextpdf.text.pdf.PdfSigLockDictionary.LockAction;
  37. import com.itextpdf.text.pdf.PdfSigLockDictionary.LockPermissions;
  38. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  39. import com.itextpdf.text.pdf.PdfStamper;
  40. import com.itextpdf.text.pdf.PdfWriter;
  41. import com.itextpdf.text.pdf.TextField;
  42. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  43. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  44. import com.itextpdf.text.pdf.security.ExternalDigest;
  45. import com.itextpdf.text.pdf.security.MakeSignature;
  46. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  47. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  48.  
  49. public class C2_12_LockFields {
  50.     public static final String FORM = "results/chapter2/form_lock.pdf";
  51.     public static final String ALICE = "src/main/resources/alice";
  52.     public static final String BOB = "src/main/resources/bob";
  53.     public static final String CAROL = "src/main/resources/carol";
  54.     public static final String DAVE = "src/main/resources/dave";
  55.     public static final char[] PASSWORD = "password".toCharArray();
  56.     public static final String DEST = "results/chapter2/step_%s_signed_by_%s.pdf";
  57.    
  58.     public class MyTextFieldEvent implements PdfPCellEvent {
  59.  
  60.         public String name;
  61.        
  62.         public MyTextFieldEvent(String name) {
  63.             this.name = name;
  64.         }
  65.  
  66.         public void cellLayout(PdfPCell cell, Rectangle position,
  67.                 PdfContentByte[] canvases) {
  68.             PdfWriter writer = canvases[0].getPdfWriter();
  69.             TextField text = new TextField(writer, position, name);
  70.             try {
  71.                 writer.addAnnotation(text.getTextField());
  72.             } catch (IOException e) {
  73.                 throw new ExceptionConverter(e);
  74.             } catch (DocumentException e) {
  75.                 throw new ExceptionConverter(e);
  76.             }
  77.         }
  78.     }
  79.    
  80.     public class MySignatureFieldEvent implements PdfPCellEvent {
  81.  
  82.         public PdfFormField field;
  83.        
  84.         public MySignatureFieldEvent(PdfFormField field) {
  85.             this.field = field;
  86.         }
  87.        
  88.         public void cellLayout(PdfPCell cell, Rectangle position,
  89.                 PdfContentByte[] canvases) {
  90.             PdfWriter writer = canvases[0].getPdfWriter();
  91.             field.setPage();
  92.             field.setWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  93.             writer.addAnnotation(field);
  94.         }
  95.        
  96.     }
  97.    
  98.     public void createForm() throws IOException, DocumentException {
  99.         Document document = new Document();
  100.         PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(FORM));
  101.         document.open();
  102.         PdfPTable table = new PdfPTable(1);
  103.         table.setWidthPercentage(100);
  104.         table.addCell("Written by Alice");
  105.         table.addCell(createSignatureFieldCell(writer, "sig1", null));
  106.         table.addCell("For approval by Bob");
  107.         table.addCell(createTextFieldCell("approved_bob"));
  108.         PdfSigLockDictionary lock = new PdfSigLockDictionary(LockAction.INCLUDE, "sig1", "approved_bob", "sig2");
  109.         table.addCell(createSignatureFieldCell(writer, "sig2", lock));
  110.         table.addCell("For approval by Carol");
  111.         table.addCell(createTextFieldCell("approved_carol"));
  112.         lock = new PdfSigLockDictionary(LockAction.EXCLUDE, "approved_dave", "sig4");
  113.         table.addCell(createSignatureFieldCell(writer, "sig3", lock));
  114.         table.addCell("For approval by Dave");
  115.         table.addCell(createTextFieldCell("approved_dave"));
  116.         lock = new PdfSigLockDictionary(LockPermissions.NO_CHANGES_ALLOWED);
  117.         table.addCell(createSignatureFieldCell(writer, "sig4", lock));
  118.         document.add(table);
  119.         document.close();
  120.     }
  121.    
  122.     protected PdfPCell createTextFieldCell(String name) {
  123.         PdfPCell cell = new PdfPCell();
  124.         cell.setMinimumHeight(20);
  125.         cell.setCellEvent(new MyTextFieldEvent(name));
  126.         return cell;
  127.     }
  128.    
  129.     protected PdfPCell createSignatureFieldCell(PdfWriter writer, String name, PdfDictionary lock) throws IOException {
  130.         PdfPCell cell = new PdfPCell();
  131.         cell.setMinimumHeight(50);
  132.         PdfFormField field = PdfFormField.createSignature(writer);
  133.         field.setFieldName(name);
  134.         if (lock != null)
  135.             field.put(PdfName.LOCK, writer.addToBody(lock).getIndirectReference());
  136.         field.setFlags(PdfAnnotation.FLAGS_PRINT);
  137.         cell.setCellEvent(new MySignatureFieldEvent(field));
  138.         return cell;
  139.     }
  140.    
  141.     public void certify(String keystore,
  142.             String src, String name, String dest)
  143.                     throws GeneralSecurityException, IOException, DocumentException {
  144.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  145.         ks.load(new FileInputStream(keystore), PASSWORD);
  146.         String alias = (String)ks.aliases().nextElement();
  147.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  148.         Certificate[] chain = ks.getCertificateChain(alias);
  149.         // Creating the reader and the stamper
  150.         PdfReader reader = new PdfReader(src);
  151.         FileOutputStream os = new FileOutputStream(dest);
  152.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  153.         // Creating the appearance
  154.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  155.         appearance.setVisibleSignature(name);
  156.         appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_FORM_FILLING);
  157.         AcroFields form = stamper.getAcroFields();
  158.         form.setFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  159.         // Creating the signature
  160.         PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
  161.         ExternalDigest digest = new BouncyCastleDigest();
  162.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  163.     }
  164.    
  165.     public void fillOutAndSign(String keystore,
  166.             String src, String name, String fname, String value, String dest)
  167.                     throws GeneralSecurityException, IOException, DocumentException {
  168.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  169.         ks.load(new FileInputStream(keystore), PASSWORD);
  170.         String alias = (String)ks.aliases().nextElement();
  171.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  172.         Certificate[] chain = ks.getCertificateChain(alias);
  173.         // Creating the reader and the stamper
  174.         PdfReader reader = new PdfReader(src);
  175.         FileOutputStream os = new FileOutputStream(dest);
  176.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  177.         AcroFields form = stamper.getAcroFields();
  178.         form.setField(fname, value);
  179.         form.setFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  180.         form.setFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
  181.         // Creating the appearance
  182.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  183.         appearance.setVisibleSignature(name);
  184.         // Creating the signature
  185.         PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
  186.         ExternalDigest digest = new BouncyCastleDigest();
  187.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  188.     }
  189.    
  190.     public void fillOut(String src, String dest, String name, String value) throws IOException, DocumentException {
  191.         PdfReader reader = new PdfReader(src);
  192.         PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest), '\0', true);
  193.         AcroFields form = stamper.getAcroFields();
  194.         form.setField(name, value);
  195.         stamper.close();
  196.     }
  197.    
  198.     public void sign(String keystore,
  199.             String src, String name, String dest)
  200.                     throws GeneralSecurityException, IOException, DocumentException {
  201.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  202.         ks.load(new FileInputStream(keystore), PASSWORD);
  203.         String alias = (String)ks.aliases().nextElement();
  204.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  205.         Certificate[] chain = ks.getCertificateChain(alias);
  206.         // Creating the reader and the stamper
  207.         PdfReader reader = new PdfReader(src);
  208.         FileOutputStream os = new FileOutputStream(dest);
  209.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, true);
  210.         // Creating the appearance
  211.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  212.         appearance.setVisibleSignature(name);
  213.         // Creating the signature
  214.         PrivateKeySignature pks = new PrivateKeySignature(pk, DigestAlgorithms.SHA256, "BC");
  215.         ExternalDigest digest = new BouncyCastleDigest();
  216.         MakeSignature.signDetached(appearance, digest, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  217.     }
  218.    
  219.     public static void main(String[] args) throws IOException, DocumentException, GeneralSecurityException {
  220.         BouncyCastleProvider provider = new BouncyCastleProvider();
  221.         Security.addProvider(provider);
  222.         C2_12_LockFields app = new C2_12_LockFields();
  223.         app.createForm();
  224.         app.certify(ALICE, FORM, "sig1", String.format(DEST, 1, "alice"));
  225.         app.fillOutAndSign(BOB, String.format(DEST, 1, "alice"), "sig2", "approved_bob", "Read and Approved by Bob", String.format(DEST, 2, "alice_and_bob"));
  226.         app.fillOutAndSign(CAROL, String.format(DEST, 2, "alice_and_bob"), "sig3", "approved_carol", "Read and Approved by Carol", String.format(DEST, 3, "alice_bob_and_carol"));
  227.         app.fillOutAndSign(DAVE, String.format(DEST, 3, "alice_bob_and_carol"), "sig4", "approved_dave", "Read and Approved by Dave", String.format(DEST, 4, "alice_bob_carol_and_dave"));
  228.         app.fillOut(String.format(DEST, 2, "alice_and_bob"), String.format(DEST, 5, "alice_and_bob_broken_by_chuck"), "approved_bob", "Changed by Chuck");
  229.         app.fillOut(String.format(DEST, 4, "alice_bob_carol_and_dave"), String.format(DEST, 6, "dave_broken_by_chuck"), "approved_carol", "Changed by Chuck");
  230.     }
  231. }
C2_01_SignHelloWorld.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_01_SignHelloWorld {
  22.  
  23.         public const String KEYSTORE = "../../../../resources/pkcs12";
  24.         public static char[] PASSWORD = "password".ToCharArray();
  25.         public const String SRC = "../../../../resources/hello.pdf";
  26.         public const String DEST = "../../../../results/chapter2/hello_signed{0}.pdf";
  27.  
  28.         public void Sign(String src, String dest, ICollection chain, ICipherParameters pk,
  29.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  30.             // Creating the reader and the stamper
  31.             PdfReader reader = new PdfReader(src);
  32.             FileStream os = new FileStream(dest, FileMode.Create);
  33.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  34.             // Creating the appearance
  35.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  36.             appearance.Reason = reason;
  37.             appearance.Location = location;
  38.             appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  39.             // Creating the signature
  40.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  41.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  42.         }
  43.  
  44.         public static void Main(String[] args) {
  45.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  46.             String alias = "";
  47.             ICollection chain = new List();
  48.             // searching for private key
  49.  
  50.             foreach (string al in store.Aliases)
  51.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  52.                     alias = al;
  53.                     break;
  54.                 }
  55.  
  56.             AsymmetricKeyEntry pk = store.GetKey(alias);
  57.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  58.                 chain.Add(c.Certificate);
  59.  
  60.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  61.             C2_01_SignHelloWorld app = new C2_01_SignHelloWorld();
  62.             app.Sign(SRC, String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  63.                      CryptoStandard.CMS, "Test 1", "Ghent");
  64.             app.Sign(SRC, String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA512,
  65.                      CryptoStandard.CMS, "Test 2", "Ghent");
  66.             app.Sign(SRC, String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
  67.                      CryptoStandard.CADES, "Test 3", "Ghent");
  68.             app.Sign(SRC, String.Format(DEST, 4), chain, parameters, DigestAlgorithms.RIPEMD160,
  69.                      CryptoStandard.CADES, "Test 4", "Ghent");
  70.         }
  71.     }
  72. }
C2_02_SignHelloWorldWithTempFile.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_02_SignHelloWorldWithTempFile {
  22.  
  23.         public const String KEYSTORE = "../../../../resources/pkcs12";
  24.         public static char[] PASSWORD = "password".ToCharArray();
  25.         public const String SRC = "../../../../resources/hello.pdf";
  26.         public const String TEMP = "../../../../results/chapter2/";
  27.         public const String DEST = "../../../../results/chapter2/hello_signed_with_temp.pdf";
  28.  
  29.         public void Sign(String src, String tmp, String dest, ICollection chain,
  30.             ICipherParameters pk, String digestAlgorithm, CryptoStandard subfilter,String reason, String location) {
  31.             // Creating the reader and the stamper
  32.             PdfReader reader = new PdfReader(src);
  33.             FileStream os = new FileStream(dest, FileMode.Create);
  34.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', tmp);
  35.             // Creating the appearance
  36.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  37.             appearance.Reason = reason;
  38.             appearance.Location = location;
  39.             appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  40.             // Creating the signature
  41.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  42.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  43.         }
  44.  
  45.         static void Main(string[] args) {
  46.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  47.             String alias = "";
  48.             ICollection chain = new List();
  49.             // searching for private key
  50.  
  51.             foreach (string al in store.Aliases)
  52.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  53.                     alias = al;
  54.                     break;
  55.                 }
  56.  
  57.             AsymmetricKeyEntry pk = store.GetKey(alias);
  58.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  59.                 chain.Add(c.Certificate);
  60.  
  61.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  62.             C2_02_SignHelloWorldWithTempFile app = new C2_02_SignHelloWorldWithTempFile();
  63.             app.Sign(SRC, TEMP, DEST, chain, parameters, DigestAlgorithms.SHA256,
  64.                      CryptoStandard.CMS, "Temp test", "Ghent");
  65.         }
  66.  
  67.     }
  68. }
C2_03_SignEmptyField.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.  
  21.     public class C2_03_SignEmptyField {
  22.  
  23.         public static String KEYSTORE = "../../../../resources/pkcs12";
  24.         public static char[] PASSWORD = "password".ToCharArray();
  25.         public static String SRC = "../../../../resources/hello_to_sign.pdf";
  26.         public static String DEST = "../../../../results/chapter2/field_signed{0}.pdf";
  27.  
  28.         public void Sign(String src, String name, String dest,
  29.                          ICollection chain, ICipherParameters pk,
  30.                          String digestAlgorithm, CryptoStandard subfilter,
  31.                          String reason, String location) {
  32.             // Creating the reader and the stamper
  33.             PdfReader reader = new PdfReader(src);
  34.             FileStream os = new FileStream(dest, FileMode.Create);
  35.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  36.             // Creating the appearance
  37.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  38.             appearance.Reason = reason;
  39.             appearance.Location = location;
  40.             appearance.SetVisibleSignature(name);
  41.             // Creating the signature
  42.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  43.             //ExternalDigest digest = new BouncyCastleDigest();
  44.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  45.         }
  46.  
  47.         public static void Main(String[] args) {
  48.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  49.             String alias = "";
  50.             ICollection chain = new List();
  51.             // searching for private key
  52.  
  53.             foreach (string al in store.Aliases) {
  54.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  55.                     alias = al;
  56.                     break;
  57.                 }
  58.             }
  59.  
  60.             AsymmetricKeyEntry pk = store.GetKey(alias);
  61.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias)) {
  62.                 chain.Add(c.Certificate);
  63.             }
  64.  
  65.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  66.             C2_03_SignEmptyField app = new C2_03_SignEmptyField();
  67.             app.Sign(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  68.                      CryptoStandard.CMS, "Test 1", "Ghent");
  69.             app.Sign(SRC, "Signature1", String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA512,
  70.                      CryptoStandard.CMS, "Test 2", "Ghent");
  71.             app.Sign(SRC, "Signature1", String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
  72.                      CryptoStandard.CADES, "Test 3", "Ghent");
  73.             app.Sign(SRC, "Signature1", String.Format(DEST, 4), chain, parameters, DigestAlgorithms.RIPEMD160,
  74.                      CryptoStandard.CADES, "Test 4", "Ghent");
  75.         }
  76.     }
  77. }
C2_04_CreateEmptyField.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.Crypto.Parameters;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.X509;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.     class C2_04_CreateEmptyField {
  21.  
  22.         public const String KEYSTORE = "../../../../resources/pkcs12";
  23.         public static char[] PASSWORD = "password".ToCharArray();
  24.         public const String SRC = "../../../../resources/hello.pdf";
  25.         public const String SIGNAME = "Signature1";
  26.         public const String DEST = "../../../../results/chapter2/field_signed.pdf";
  27.         public const String UNSIGNED = "../../../../results/chapter2/hello_empty.pdf";
  28.         public const String UNSIGNED2 = "../../../../results/chapter2/hello_empty.pdf2";
  29.  
  30.         public void CreatePdf(String filename) {
  31.             // step 1: Create a Document
  32.             Document document = new Document();
  33.             // step 2: Create a PdfWriter
  34.             PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
  35.             // step 3: Open the Document
  36.             document.Open();
  37.             // step 4: Add content
  38.             document.Add(new Paragraph("Hello World!"));
  39.             // create a signature form field
  40.             PdfFormField field = PdfFormField.CreateSignature(writer);
  41.             field.FieldName = SIGNAME;
  42.             // set the widget properties
  43.             field.SetPage();
  44.             field.SetWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_INVERT);
  45.             field.Flags = PdfAnnotation.FLAGS_PRINT;
  46.             // add it as an annotation
  47.             writer.AddAnnotation(field);
  48.             // maybe you want to define an appearance
  49.             PdfAppearance tp = PdfAppearance.CreateAppearance(writer, 72, 48);
  50.             tp.SetColorStroke(BaseColor.BLUE);
  51.             tp.SetColorFill(BaseColor.LIGHT_GRAY);
  52.             tp.Rectangle(0.5f, 0.5f, 71.5f, 47.5f);
  53.             tp.FillStroke();
  54.             tp.SetColorFill(BaseColor.BLUE);
  55.             ColumnText.ShowTextAligned(tp, Element.ALIGN_CENTER, new Phrase("SIGN HERE"), 36, 24, 25);
  56.             field.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, tp);
  57.             // step 5: Close the Document
  58.             document.Close();
  59.         }
  60.  
  61.         public void AddField(String src, String dest) {
  62.             PdfReader reader = new PdfReader(src);
  63.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
  64.             // create a signature form field
  65.             PdfFormField field = PdfFormField.CreateSignature(stamper.Writer);
  66.             field.FieldName = SIGNAME;
  67.             // set the widget properties
  68.             field.SetWidget(new Rectangle(72, 732, 144, 780), PdfAnnotation.HIGHLIGHT_OUTLINE);
  69.             field.Flags = PdfAnnotation.FLAGS_PRINT;
  70.             // add the annotation
  71.             stamper.AddAnnotation(field, 1);
  72.             // close the stamper
  73.             stamper.Close();
  74.         }
  75.  
  76.         static void Main(string[] args) {
  77.             C2_04_CreateEmptyField appCreate = new C2_04_CreateEmptyField();
  78.             appCreate.CreatePdf(UNSIGNED);
  79.             appCreate.AddField(SRC, UNSIGNED2);
  80.  
  81.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  82.             String alias = "";
  83.             ICollection chain = new List();
  84.             // searching for private key
  85.  
  86.             foreach (string al in store.Aliases)
  87.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
  88.                 {
  89.                     alias = al;
  90.                     break;
  91.                 }
  92.  
  93.             AsymmetricKeyEntry pk = store.GetKey(alias);
  94.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  95.                 chain.Add(c.Certificate);
  96.  
  97.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  98.             C2_03_SignEmptyField appSign = new C2_03_SignEmptyField();
  99.             appSign.Sign(UNSIGNED, SIGNAME, DEST, chain, parameters, DigestAlgorithms.SHA256, CryptoStandard.CMS, "Test", "Ghent");
  100.         }
  101.  
  102.     }
  103. }
C2_05_CustomAppearance.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_05_CustomAppearance {
  22.         public const String KEYSTORE = "../../../../resources/pkcs12";
  23.         public static char[] PASSWORD = "password".ToCharArray();
  24.         public const String SRC = "../../../../resources/hello_to_sign.pdf";
  25.         public const String DEST = "../../../../results/chapter2/signature_custom.pdf";
  26.  
  27.         public void Sign(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  28.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  29.             // Creating the reader and the stamper
  30.             PdfReader reader = new PdfReader(src);
  31.             FileStream os = new FileStream(dest, FileMode.Create);
  32.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  33.             // Creating the appearance
  34.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  35.             appearance.Reason = reason;
  36.             appearance.Location = location;
  37.             appearance.SetVisibleSignature(name);
  38.             // Creating the appearance for layer 0
  39.             PdfTemplate n0 = appearance.GetLayer(0);
  40.             float x = n0.BoundingBox.Left;
  41.             float y = n0.BoundingBox.Bottom;
  42.             float width = n0.BoundingBox.Width;
  43.             float height = n0.BoundingBox.Height;
  44.             n0.SetColorFill(BaseColor.LIGHT_GRAY);
  45.             n0.Rectangle(x, y, width, height);
  46.             n0.Fill();
  47.             // Creating the appearance for layer 2
  48.             PdfTemplate n2 = appearance.GetLayer(2);
  49.             ColumnText ct = new ColumnText(n2);
  50.             ct.SetSimpleColumn(n2.BoundingBox);
  51.             Paragraph p = new Paragraph("This document was signed by Bruno Specimen.");
  52.             ct.AddElement(p);
  53.             ct.Go();
  54.             // Creating the signature
  55.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  56.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  57.         }
  58.  
  59.         static void Main(string[] args) {
  60.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  61.             String alias = "";
  62.             ICollection chain = new List();
  63.             // searching for private key
  64.  
  65.             foreach (string al in store.Aliases)
  66.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  67.                     alias = al;
  68.                     break;
  69.                 }
  70.  
  71.             AsymmetricKeyEntry pk = store.GetKey(alias);
  72.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  73.                 chain.Add(c.Certificate);
  74.  
  75.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  76.             C2_05_CustomAppearance app = new C2_05_CustomAppearance();
  77.             app.Sign(SRC, "Signature1", DEST, chain, parameters, DigestAlgorithms.SHA256,
  78.                      CryptoStandard.CMS, "Custom appearance example", "Ghent");
  79.         }
  80.     }
  81. }
C2_06_SignatureAppearance.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_06_SignatureAppearance {
  22.         public const String KEYSTORE = "../../../../resources/pkcs12";
  23.         public static char[] PASSWORD = "password".ToCharArray();
  24.         public const String SRC = "../../../../resources/hello_to_sign.pdf";
  25.         public const String DEST = "../../../../results/chapter2/signature_appearance{0}.pdf";
  26.         public const String IMG = "../../../../resources/1t3xt.gif";
  27.  
  28.         public void Sign1(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  29.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  30.             // Creating the reader and the stamper
  31.             PdfReader reader = new PdfReader(src);
  32.             FileStream os = new FileStream(dest, FileMode.Create);
  33.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  34.             // Creating the appearance
  35.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  36.             appearance.Reason = reason;
  37.             appearance.Location = location;
  38.             appearance.SetVisibleSignature(name);
  39.             // Custom text and custom font
  40.             appearance.Layer2Text = "This document was signed by Bruno Specimen";
  41.             appearance.Layer2Font = new Font(Font.FontFamily.TIMES_ROMAN);
  42.             // Creating the signature
  43.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  44.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  45.         }
  46.  
  47.         public void Sign2(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  48.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  49.             // Creating the reader and the stamper
  50.             PdfReader reader = new PdfReader(src);
  51.             FileStream os = new FileStream(dest, FileMode.Create);
  52.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  53.             // Creating the appearance
  54.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  55.             appearance.Reason = reason;
  56.             appearance.Location = location;
  57.             appearance.SetVisibleSignature(name);
  58.             // Custom text, custom font, and right-to-left writing
  59.             appearance.Layer2Text = "\u0644\u0648\u0631\u0627\u0646\u0633 \u0627\u0644\u0639\u0631\u0628";
  60.             appearance.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
  61.             appearance.Layer2Font = new Font(BaseFont.CreateFont("C:/windows/fonts/arialuni.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 12);
  62.             // Creating the signature
  63.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  64.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  65.         }
  66.  
  67.         public void Sign3(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  68.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  69.             // Creating the reader and the stamper
  70.             PdfReader reader = new PdfReader(src);
  71.             FileStream os = new FileStream(dest, FileMode.Create);
  72.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  73.             // Creating the appearance
  74.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  75.             appearance.Reason = reason;
  76.             appearance.Location = location;
  77.             appearance.SetVisibleSignature(name);
  78.             // Custom text and background image
  79.             appearance.Layer2Text = "This document was signed by Bruno Specimen";
  80.             appearance.Image = Image.GetInstance(IMG);
  81.             appearance.ImageScale = 1;
  82.             // Creating the signature
  83.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  84.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  85.         }
  86.  
  87.         public void Sign4(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  88.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  89.             // Creating the reader and the stamper
  90.             PdfReader reader = new PdfReader(src);
  91.             FileStream os = new FileStream(dest, FileMode.Create);
  92.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  93.             // Creating the appearance
  94.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  95.             appearance.Reason = reason;
  96.             appearance.Location = location;
  97.             appearance.SetVisibleSignature(name);
  98.             // Default text and scaled background image
  99.             appearance.Image = Image.GetInstance(IMG);
  100.             appearance.ImageScale = -1;
  101.             // Creating the signature
  102.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  103.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  104.         }
  105.  
  106.         static void Main(string[] args) {
  107.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  108.             String alias = "";
  109.             ICollection chain = new List();
  110.             // searching for private key
  111.  
  112.             foreach (string al in store.Aliases)
  113.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate)
  114.                 {
  115.                     alias = al;
  116.                     break;
  117.                 }
  118.  
  119.             AsymmetricKeyEntry pk = store.GetKey(alias);
  120.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  121.                 chain.Add(c.Certificate);
  122.  
  123.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  124.             C2_06_SignatureAppearance app = new C2_06_SignatureAppearance();
  125.             app.Sign1(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  126.                      CryptoStandard.CMS, "Custom appearance example", "Ghent");
  127.             app.Sign2(SRC, "Signature1", String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA256,
  128.                      CryptoStandard.CMS, "Custom appearance example", "Ghent");
  129.             app.Sign3(SRC, "Signature1", String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
  130.                      CryptoStandard.CMS, "Custom appearance example", "Ghent");
  131.             app.Sign4(SRC, "Signature1", String.Format(DEST, 4), chain, parameters, DigestAlgorithms.SHA256,
  132.                      CryptoStandard.CMS, "Custom appearance example", "Ghent");
  133.         }
  134.     }
  135. }
C2_07_SignatureAppearances.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_07_SignatureAppearances {
  22.         public const String KEYSTORE = "../../../../resources/pkcs12";
  23.         public static char[] PASSWORD = "password".ToCharArray();
  24.         public const String SRC = "../../../../resources/hello_to_sign.pdf";
  25.         public const String DEST = "../../../../results/chapter2/signature_appearance{0}.pdf";
  26.         public const String IMG = "../../../../resources/1t3xt.gif";
  27.  
  28.         public void Sign(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  29.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
  30.                          PdfSignatureAppearance.RenderingMode renderingMode, Image image) {
  31.             // Creating the reader and the stamper
  32.             PdfReader reader = new PdfReader(src);
  33.             FileStream os = new FileStream(dest, FileMode.Create);
  34.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  35.             // Creating the appearance
  36.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  37.             appearance.Reason = reason;
  38.             appearance.Location = location;
  39.             appearance.SetVisibleSignature(name);
  40.             appearance.Layer2Text = "Signed on " + DateTime.Now;
  41.             appearance.SignatureRenderingMode = renderingMode;
  42.             appearance.SignatureGraphic = image;
  43.             // Creating the signature
  44.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  45.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  46.         }
  47.  
  48.         static void Main(string[] args) {
  49.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  50.             String alias = "";
  51.             ICollection chain = new List();
  52.             // searching for private key
  53.  
  54.             foreach (string al in store.Aliases)
  55.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  56.                     alias = al;
  57.                     break;
  58.                 }
  59.  
  60.             AsymmetricKeyEntry pk = store.GetKey(alias);
  61.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  62.                 chain.Add(c.Certificate);
  63.             Image image = Image.GetInstance(IMG);
  64.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  65.             C2_07_SignatureAppearances app = new C2_07_SignatureAppearances();
  66.             app.Sign(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  67.                      CryptoStandard.CMS, "Appearance 1", "Ghent", PdfSignatureAppearance.RenderingMode.DESCRIPTION, null);
  68.             app.Sign(SRC, "Signature1", String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA256,
  69.                      CryptoStandard.CMS, "Appearance 2", "Ghent", PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION, null);
  70.             app.Sign(SRC, "Signature1", String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
  71.                      CryptoStandard.CMS, "Appearance 3", "Ghent", PdfSignatureAppearance.RenderingMode.GRAPHIC_AND_DESCRIPTION, image);
  72.             app.Sign(SRC, "Signature1", String.Format(DEST, 4), chain, parameters, DigestAlgorithms.SHA256,
  73.                      CryptoStandard.CMS, "Appearance 4", "Ghent", PdfSignatureAppearance.RenderingMode.GRAPHIC, image);
  74.         }
  75.     }
  76. }
C2_08_SignatureMetadata.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.     class C2_08_SignatureMetadata {
  21.         public const String KEYSTORE = "../../../../resources/pkcs12";
  22.         public static char[] PASSWORD = "password".ToCharArray();
  23.         public const String SRC = "../../../../resources/hello_to_sign.pdf";
  24.         public const String DEST = "../../../../results/chapter2/field_metadata.pdf";
  25.  
  26.         class MySignatureEvent : PdfSignatureAppearance.ISignatureEvent {
  27.             private String fullName;
  28.  
  29.             public String FullName {
  30.                 set { fullName = value; }
  31.             }
  32.  
  33.             public void GetSignatureDictionary(PdfDictionary sig) {
  34.                 sig.Put(PdfName.NAME, new PdfString(fullName));
  35.             }
  36.         }
  37.  
  38.         public void Sign(String src, String name, String dest, ICollection chain, ICipherParameters pk,
  39.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
  40.                          String contact, DateTime signDate, String fullName) {
  41.             // Creating the reader and the stamper
  42.             PdfReader reader = new PdfReader(src);
  43.             FileStream os = new FileStream(dest, FileMode.Create);
  44.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  45.             // Creating the appearance
  46.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  47.             appearance.Reason = reason;
  48.             appearance.Location = location;
  49.             appearance.SetVisibleSignature(name);
  50.             appearance.Contact = contact;
  51.             appearance.SignDate = signDate;
  52.             MySignatureEvent eEvent = new MySignatureEvent();
  53.             eEvent.FullName = fullName;
  54.             appearance.SignatureEvent = eEvent;
  55.             // Creating the signature
  56.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  57.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  58.         }
  59.  
  60.         static void Main(string[] args) {
  61.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  62.             String alias = "";
  63.             ICollection chain = new List();
  64.             // searching for private key
  65.  
  66.             foreach (string al in store.Aliases)
  67.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  68.                     alias = al;
  69.                     break;
  70.                 }
  71.  
  72.             AsymmetricKeyEntry pk = store.GetKey(alias);
  73.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  74.                 chain.Add(c.Certificate);
  75.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  76.             C2_08_SignatureMetadata app = new C2_08_SignatureMetadata();
  77.             app.Sign(SRC, "Signature1", String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  78.                      CryptoStandard.CMS, "Appearance 1", "Ghent", "555 123 456", new DateTime(2012, 8, 5), "Bruno L. Specimen");
  79.         }
  80.     }
  81. }
C2_09_SignatureTypes.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.Crypto;
  13. using Org.BouncyCastle.Crypto.Parameters;
  14. using Org.BouncyCastle.Pkcs;
  15. using Org.BouncyCastle.X509;
  16. using iTextSharp.text;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19.  
  20. namespace signatures.chapter2 {
  21.     class C2_09_SignatureTypes {
  22.         public const String KEYSTORE = "../../../../resources/pkcs12";
  23.         public static char[] PASSWORD = "password".ToCharArray();
  24.         public const String SRC = "../../../../resources/hello.pdf";
  25.         public const String DEST = "../../../../results/chapter2/hello_level_{0}.pdf";
  26.  
  27.         public void Sign(String src, String dest, ICollection chain, ICipherParameters pk,
  28.                 String digestAlgorithm, CryptoStandard subfilter, int certificationLevel, String reason, String location) {
  29.             // Creating the reader and the stamper
  30.             PdfReader reader = new PdfReader(src);
  31.             FileStream os = new FileStream(dest, FileMode.Create);
  32.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  33.             // Creating the appearance
  34.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  35.             appearance.Reason = reason;
  36.             appearance.Location = location;
  37.             appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  38.             appearance.CertificationLevel = certificationLevel;
  39.             // Creating the signature
  40.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  41.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  42.         }
  43.  
  44.         public void AddText(String src, String dest) {
  45.             PdfReader reader = new PdfReader(src);
  46.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create), '\0', true);
  47.             ColumnText.ShowTextAligned(stamper.GetOverContent(1), Element.ALIGN_LEFT, new Phrase("TOP SECRET"), 36, 820, 0);
  48.             stamper.Close();
  49.         }
  50.        
  51.         public void AddAnnotation(String src, String dest) {
  52.             PdfReader reader = new PdfReader(src);
  53.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create), '\0', true);
  54.             PdfAnnotation comment = PdfAnnotation.CreateText(stamper.Writer,
  55.                     new Rectangle(200, 800, 250, 820), "Finally Signed!",
  56.                     "Bruno Specimen has finally signed the document", true, "Comment");
  57.             stamper.AddAnnotation(comment, 1);
  58.             stamper.Close();
  59.         }
  60.        
  61.         public void AddWrongAnnotation(String src, String dest) {
  62.             PdfReader reader = new PdfReader(src);
  63.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create));
  64.             PdfAnnotation comment = PdfAnnotation.CreateText(stamper.Writer,
  65.                     new Rectangle(200, 800, 250, 820), "Finally Signed!",
  66.                     "Bruno Specimen has finally signed the document", true, "Comment");
  67.             stamper.AddAnnotation(comment, 1);
  68.             stamper.Close();
  69.         }
  70.  
  71.         public void SignAgain(String src, String dest, ICollection chain, ICipherParameters pk,
  72.                String digestAlgorithm, CryptoStandard subfilter, String reason, String location) {
  73.             // Creating the reader and the stamper
  74.             PdfReader reader = new PdfReader(src);
  75.             FileStream os = new FileStream(dest, FileMode.Create);
  76.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  77.             // Creating the appearance
  78.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  79.             appearance.Reason = reason;
  80.             appearance.Location = location;
  81.             appearance.SetVisibleSignature(new Rectangle(36, 700, 144, 732), 1, "Signature2");
  82.             // Creating the signature
  83.             IExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm);
  84.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, subfilter);
  85.         }
  86.  
  87.         public static void Main(String[] args) {
  88.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  89.             String alias = "";
  90.             ICollection chain = new List();
  91.             // searching for private key
  92.  
  93.             foreach (string al in store.Aliases)
  94.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  95.                     alias = al;
  96.                     break;
  97.                 }
  98.  
  99.             AsymmetricKeyEntry pk = store.GetKey(alias);
  100.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  101.                 chain.Add(c.Certificate);
  102.  
  103.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  104.             C2_09_SignatureTypes app = new C2_09_SignatureTypes();
  105.             app.Sign(SRC, String.Format(DEST, 1), chain, parameters, DigestAlgorithms.SHA256,
  106.                      CryptoStandard.CMS, PdfSignatureAppearance.NOT_CERTIFIED, "Test 1", "Ghent");
  107.             app.Sign(SRC, String.Format(DEST, 2), chain, parameters, DigestAlgorithms.SHA512,
  108.                      CryptoStandard.CMS, PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS, "Test 1", "Ghent");
  109.             app.Sign(SRC, String.Format(DEST, 3), chain, parameters, DigestAlgorithms.SHA256,
  110.                      CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, "Test 1", "Ghent");
  111.             app.Sign(SRC, String.Format(DEST, 4), chain, parameters, DigestAlgorithms.RIPEMD160,
  112.                      CryptoStandard.CADES, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, "Test 1", "Ghent");
  113.  
  114.             app.AddWrongAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated_wrong"));
  115.             app.AddAnnotation(String.Format(DEST, 1), String.Format(DEST, "1_annotated"));
  116.             app.AddAnnotation(String.Format(DEST, 2), String.Format(DEST, "2_annotated"));
  117.             app.AddAnnotation(String.Format(DEST, 3), String.Format(DEST, "3_annotated"));
  118.             app.AddAnnotation(String.Format(DEST, 4), String.Format(DEST, "4_annotated"));
  119.             app.AddText(String.Format(DEST, 1), String.Format(DEST, "1_text"));
  120.  
  121.             app.SignAgain(String.Format(DEST, 1), String.Format(DEST, "1_double"), chain, parameters, DigestAlgorithms.SHA256,
  122.                      CryptoStandard.CMS, "Second signature test", "Ghent");
  123.             app.SignAgain(String.Format(DEST, 2), String.Format(DEST, "2_double"), chain, parameters, DigestAlgorithms.SHA256,
  124.                      CryptoStandard.CMS, "Second signature test", "Ghent");
  125.             app.SignAgain(String.Format(DEST, 3), String.Format(DEST, "3_double"), chain, parameters, DigestAlgorithms.SHA256,
  126.                      CryptoStandard.CMS, "Second signature test", "Ghent");
  127.             app.SignAgain(String.Format(DEST, 4), String.Format(DEST, "4_double"), chain, parameters, DigestAlgorithms.SHA256,
  128.                      CryptoStandard.CMS, "Second signature test", "Ghent");
  129.         }
  130.     }
  131. }
C2_10_SequentialSignatures.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.Crypto.Parameters;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.X509;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.     class C2_10_SequentialSignatures {
  21.         public const String FORM = "../../../../results/chapter2/multiple_signatures.pdf";
  22.         public const String ALICE = "../../../../resources/alice";
  23.         public const String BOB = "../../../../resources/bob";
  24.         public const String CAROL = "../../../../resources/carol";
  25.         public static char[] PASSWORD = "password".ToCharArray();
  26.         public const String DEST = "../../../../results/chapter2/signed_by_{0}.pdf";
  27.  
  28.         public void CreateForm() {
  29.             Document document = new Document();
  30.             PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FORM, FileMode.Create));
  31.             document.Open();
  32.             PdfPTable table = new PdfPTable(1);
  33.             table.WidthPercentage = 100;
  34.             table.AddCell("Signer 1: Alice");
  35.             table.AddCell(CreateSignatureFieldCell(writer, "sig1"));
  36.             table.AddCell("Signer 2: Bob");
  37.             table.AddCell(CreateSignatureFieldCell(writer, "sig2"));
  38.             table.AddCell("Signer 3: Carol");
  39.             table.AddCell(CreateSignatureFieldCell(writer, "sig3"));
  40.             document.Add(table);
  41.             document.Close();
  42.         }
  43.        
  44.         protected PdfPCell CreateSignatureFieldCell(PdfWriter writer, String name) {
  45.             PdfPCell cell = new PdfPCell();
  46.             cell.MinimumHeight = 50;
  47.             PdfFormField field = PdfFormField.CreateSignature(writer);
  48.             field.FieldName = name;
  49.             field.Flags = PdfAnnotation.FLAGS_PRINT;
  50.             cell.CellEvent = new MySignatureFieldEvent(field);
  51.             return cell;
  52.         }
  53.        
  54.         public class MySignatureFieldEvent : IPdfPCellEvent {
  55.             public PdfFormField field;
  56.            
  57.             public MySignatureFieldEvent(PdfFormField field) {
  58.                 this.field = field;
  59.             }
  60.            
  61.             public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  62.                 PdfWriter writer = canvases[0].PdfWriter;
  63.                 field.SetPage();
  64.                 field.SetWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  65.                 writer.AddAnnotation(field);
  66.             }
  67.         }
  68.  
  69.         public void Sign(String keystore, int level, String src, String name, String dest) {
  70.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  71.             String alias = "";
  72.             ICollection chain = new List();
  73.             // searching for private key
  74.             foreach (string al in store.Aliases)
  75.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  76.                     alias = al;
  77.                     break;
  78.                 }
  79.             AsymmetricKeyEntry pk = store.GetKey(alias);
  80.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  81.                 chain.Add(c.Certificate);
  82.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  83.  
  84.             PdfReader reader = new PdfReader(src);
  85.             FileStream os = new FileStream(dest, FileMode.Create);
  86.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  87.             // Creating the appearance
  88.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  89.             appearance.SetVisibleSignature(name);
  90.             appearance.CertificationLevel = level;
  91.             // Creating the signature
  92.             IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");
  93.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  94.         }
  95.  
  96.         static void Main(string[] args) {
  97.             C2_10_SequentialSignatures app = new C2_10_SequentialSignatures();
  98.             app.CreateForm();
  99.  
  100.             app.Sign(ALICE, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, FORM, "sig1", String.Format(DEST, "alice"));
  101.             app.Sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.Format(DEST, "alice"), "sig2", String.Format(DEST, "bob"));
  102.             app.Sign(CAROL, PdfSignatureAppearance.NOT_CERTIFIED, String.Format(DEST, "bob"), "sig3", String.Format(DEST, "carol"));
  103.  
  104.             app.Sign(ALICE, PdfSignatureAppearance.NOT_CERTIFIED, FORM, "sig1", String.Format(DEST, "alice2"));
  105.             app.Sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.Format(DEST, "alice2"), "sig2", String.Format(DEST, "bob2"));
  106.             app.Sign(CAROL, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, String.Format(DEST, "bob2"), "sig3", String.Format(DEST, "carol2"));
  107.  
  108.             app.Sign(ALICE, PdfSignatureAppearance.NOT_CERTIFIED, FORM, "sig1", String.Format(DEST, "alice3"));
  109.             app.Sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.Format(DEST, "alice3"), "sig2", String.Format(DEST, "bob3"));
  110.             app.Sign(CAROL, PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED, String.Format(DEST, "bob3"), "sig3", String.Format(DEST, "carol3"));
  111.  
  112.             app.Sign(ALICE, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, FORM, "sig1", String.Format(DEST, "alice4"));
  113.             app.Sign(BOB, PdfSignatureAppearance.NOT_CERTIFIED, String.Format(DEST, "alice4"), "sig2", String.Format(DEST, "bob4"));
  114.             app.Sign(CAROL, PdfSignatureAppearance.CERTIFIED_FORM_FILLING, String.Format(DEST, "bob4"), "sig3", String.Format(DEST, "carol4"));
  115.         }
  116.     }
  117. }
C2_11_SignatureWorkflow.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.Crypto.Parameters;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.X509;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.     class C2_11_SignatureWorkflow {
  21.         public const String FORM = "../../../../results/chapter2/form.pdf";
  22.         public const String ALICE = "../../../../resources/alice";
  23.         public const String BOB = "../../../../resources/bob";
  24.         public const String CAROL = "../../../../resources/carol";
  25.         public const String DAVE = "../../../../resources/dave";
  26.         public static char[] PASSWORD = "password".ToCharArray();
  27.         public const String DEST = "../../../../results/chapter2/step{0}_signed_by_{1}.pdf";
  28.  
  29.         public class MyTextFieldEvent : IPdfPCellEvent {
  30.             public String name;
  31.            
  32.             public MyTextFieldEvent(String name) {
  33.                 this.name = name;
  34.             }
  35.  
  36.             public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  37.                 PdfWriter writer = canvases[0].PdfWriter;
  38.                 TextField text = new TextField(writer, position, name);
  39.                 writer.AddAnnotation(text.GetTextField());
  40.             }
  41.         }
  42.        
  43.         public class MySignatureFieldEvent : IPdfPCellEvent {
  44.             public PdfFormField field;
  45.            
  46.             public MySignatureFieldEvent(PdfFormField field) {
  47.                 this.field = field;
  48.             }
  49.            
  50.             public void CellLayout(PdfPCell cell, Rectangle position,
  51.                     PdfContentByte[] canvases) {
  52.                 PdfWriter writer = canvases[0].PdfWriter;
  53.                 field.SetPage();
  54.                 field.SetWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  55.                 writer.AddAnnotation(field);
  56.             }
  57.         }
  58.        
  59.         public void CreateForm() {
  60.             Document document = new Document();
  61.             PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FORM, FileMode.Create));
  62.             document.Open();
  63.             PdfPTable table = new PdfPTable(1);
  64.             table.WidthPercentage = 100;
  65.             table.AddCell("Written by Alice");
  66.             table.AddCell(CreateSignatureFieldCell(writer, "sig1"));
  67.             table.AddCell("For approval by Bob");
  68.             table.AddCell(CreateTextFieldCell("approved_bob"));
  69.             table.AddCell(CreateSignatureFieldCell(writer, "sig2"));
  70.             table.AddCell("For approval by Carol");
  71.             table.AddCell(CreateTextFieldCell("approved_carol"));
  72.             table.AddCell(CreateSignatureFieldCell(writer, "sig3"));
  73.             table.AddCell("For approval by Dave");
  74.             table.AddCell(CreateTextFieldCell("approved_dave"));
  75.             table.AddCell(CreateSignatureFieldCell(writer, "sig4"));
  76.             document.Add(table);
  77.             document.Close();
  78.         }
  79.        
  80.         protected PdfPCell CreateTextFieldCell(String name) {
  81.             PdfPCell cell = new PdfPCell();
  82.             cell.MinimumHeight = 20;
  83.             cell.CellEvent = new MyTextFieldEvent(name);
  84.             return cell;
  85.         }
  86.        
  87.         protected PdfPCell CreateSignatureFieldCell(PdfWriter writer, String name) {
  88.             PdfPCell cell = new PdfPCell();
  89.             cell.MinimumHeight = 50;
  90.             PdfFormField field = PdfFormField.CreateSignature(writer);
  91.             field.FieldName = name;
  92.             field.Flags = PdfAnnotation.FLAGS_PRINT;
  93.             cell.CellEvent = new MySignatureFieldEvent(field);
  94.             return cell;
  95.         }
  96.        
  97.         public void Certify(String keystore, String src, String name, String dest) {
  98.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  99.             String alias = "";
  100.             ICollection chain = new List();
  101.             // searching for private key
  102.             foreach (string al in store.Aliases)
  103.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  104.                     alias = al;
  105.                     break;
  106.                 }
  107.             AsymmetricKeyEntry pk = store.GetKey(alias);
  108.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  109.                 chain.Add(c.Certificate);
  110.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  111.  
  112.             PdfReader reader = new PdfReader(src);
  113.             FileStream os = new FileStream(dest, FileMode.Create);
  114.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  115.             // Creating the appearance
  116.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  117.             appearance.SetVisibleSignature(name);
  118.             appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING;
  119.             // Creating the signature
  120.             IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");
  121.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  122.         }
  123.        
  124.         public void FillOut(String src, String dest, String name, String value) {
  125.             PdfReader reader = new PdfReader(src);
  126.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create), '\0', true);
  127.             AcroFields form = stamper.AcroFields;
  128.             form.SetField(name, value);
  129.             form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  130.             stamper.Close();
  131.         }
  132.        
  133.         public void Sign(String keystore, String src, String name, String dest) {
  134.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  135.             String alias = "";
  136.             ICollection chain = new List();
  137.             // searching for private key
  138.             foreach (string al in store.Aliases)
  139.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  140.                     alias = al;
  141.                     break;
  142.                 }
  143.             AsymmetricKeyEntry pk = store.GetKey(alias);
  144.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  145.                 chain.Add(c.Certificate);
  146.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  147.  
  148.             PdfReader reader = new PdfReader(src);
  149.             FileStream os = new FileStream(dest, FileMode.Create);
  150.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  151.             // Creating the appearance
  152.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  153.             appearance.SetVisibleSignature(name);
  154.             // Creating the signature
  155.             IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");
  156.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  157.         }
  158.        
  159.         public void FillOutAndSign(String keystore, String src, String name, String fname, String value, String dest) {
  160.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  161.             String alias = "";
  162.             ICollection chain = new List();
  163.             // searching for private key
  164.             foreach (string al in store.Aliases)
  165.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  166.                     alias = al;
  167.                     break;
  168.                 }
  169.             AsymmetricKeyEntry pk = store.GetKey(alias);
  170.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  171.                 chain.Add(c.Certificate);
  172.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  173.  
  174.             PdfReader reader = new PdfReader(src);
  175.             FileStream os = new FileStream(dest, FileMode.Create);
  176.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  177.             AcroFields form = stamper.AcroFields;
  178.             form.SetField(fname, value);
  179.             form.SetFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
  180.             // Creating the appearance
  181.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  182.             appearance.SetVisibleSignature(name);
  183.             // Creating the signature
  184.             IExternalSignature pks = new PrivateKeySignature(parameters, "SHA-256");
  185.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  186.         }
  187.        
  188.         public static void Main(String[] args) {
  189.             C2_11_SignatureWorkflow app = new C2_11_SignatureWorkflow();
  190.             app.CreateForm();
  191.             app.Certify(ALICE, FORM, "sig1", String.Format(DEST, 1, "alice"));
  192.             app.FillOut(String.Format(DEST, 1, "alice"), String.Format(DEST, 2, "alice_and_filled_out_by_bob"), "approved_bob", "Read and Approved by Bob");
  193.             app.Sign(BOB, String.Format(DEST, 2, "alice_and_filled_out_by_bob"), "sig2", String.Format(DEST, 3, "alice_and_bob"));
  194.             app.FillOut(String.Format(DEST, 3, "alice_and_bob"), String.Format(DEST, 4, "alice_and_bob_filled_out_by_carol"), "approved_carol", "Read and Approved by Carol");
  195.             app.Sign(CAROL, String.Format(DEST, 4, "alice_and_bob_filled_out_by_carol"), "sig3", String.Format(DEST, 5, "alice_bob_and_carol"));
  196.             app.FillOutAndSign(DAVE, String.Format(DEST, 5, "alice_bob_and_carol"), "sig4", "approved_dave", "Read and Approved by Dave", String.Format(DEST, 6, "alice_bob_carol_and_dave"));
  197.         }
  198.     }
  199. }
C2_12_LockFields.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.Crypto.Parameters;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.X509;
  15. using iTextSharp.text;
  16. using iTextSharp.text.pdf;
  17. using iTextSharp.text.pdf.security;
  18.  
  19. namespace signatures.chapter2 {
  20.     class C2_12_LockFields {
  21.         public const String FORM = "../../../../results/chapter2/form_lock.pdf";
  22.         public const String ALICE = "../../../../resources/alice";
  23.         public const String BOB = "../../../../resources/bob";
  24.         public const String CAROL = "../../../../resources/carol";
  25.         public const String DAVE = "../../../../resources/dave";
  26.         public static char[] PASSWORD = "password".ToCharArray();
  27.         public const String DEST = "../../../../results/chapter2/step_{0}_signed_by_{1}.pdf";
  28.  
  29.         public class MyTextFieldEvent : IPdfPCellEvent {
  30.             public String name;
  31.            
  32.             public MyTextFieldEvent(String name) {
  33.                 this.name = name;
  34.             }
  35.  
  36.             public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  37.                 PdfWriter writer = canvases[0].PdfWriter;
  38.                 TextField text = new TextField(writer, position, name);
  39.                 writer.AddAnnotation(text.GetTextField());
  40.             }
  41.         }
  42.        
  43.         public class MySignatureFieldEvent : IPdfPCellEvent {
  44.             public PdfFormField field;
  45.            
  46.             public MySignatureFieldEvent(PdfFormField field) {
  47.                 this.field = field;
  48.             }
  49.            
  50.             public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
  51.                 PdfWriter writer = canvases[0].PdfWriter;
  52.                 field.SetPage();
  53.                 field.SetWidget(position, PdfAnnotation.HIGHLIGHT_INVERT);
  54.                 writer.AddAnnotation(field);
  55.             }
  56.         }
  57.        
  58.         public void CreateForm() {
  59.             Document document = new Document();
  60.             PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(FORM, FileMode.Create));
  61.             document.Open();
  62.             PdfPTable table = new PdfPTable(1);
  63.             table.WidthPercentage = 100;
  64.             table.AddCell("Written by Alice");
  65.             table.AddCell(CreateSignatureFieldCell(writer, "sig1", null));
  66.             table.AddCell("For approval by Bob");
  67.             table.AddCell(CreateTextFieldCell("approved_bob"));
  68.             PdfSigLockDictionary Lock = new PdfSigLockDictionary(PdfSigLockDictionary.LockAction.INCLUDE, "sig1", "approved_bob", "sig2");
  69.             table.AddCell(CreateSignatureFieldCell(writer, "sig2", Lock));
  70.             table.AddCell("For approval by Carol");
  71.             table.AddCell(CreateTextFieldCell("approved_carol"));
  72.             Lock = new PdfSigLockDictionary(PdfSigLockDictionary.LockAction.EXCLUDE, "approved_dave", "sig4");
  73.             table.AddCell(CreateSignatureFieldCell(writer, "sig3", Lock));
  74.             table.AddCell("For approval by Dave");
  75.             table.AddCell(CreateTextFieldCell("approved_dave"));
  76.             Lock = new PdfSigLockDictionary(PdfSigLockDictionary.LockPermissions.NO_CHANGES_ALLOWED);
  77.             table.AddCell(CreateSignatureFieldCell(writer, "sig4", Lock));
  78.             document.Add(table);
  79.             document.Close();
  80.         }
  81.        
  82.         protected PdfPCell CreateTextFieldCell(String name) {
  83.             PdfPCell cell = new PdfPCell();
  84.             cell.MinimumHeight = 20;
  85.             cell.CellEvent = new MyTextFieldEvent(name);
  86.             return cell;
  87.         }
  88.        
  89.         protected PdfPCell CreateSignatureFieldCell(PdfWriter writer, String name, PdfDictionary Lock) {
  90.             PdfPCell cell = new PdfPCell();
  91.             cell.MinimumHeight = 50;
  92.             PdfFormField field = PdfFormField.CreateSignature(writer);
  93.             field.FieldName = name;
  94.             if (Lock != null)
  95.                 field.Put(PdfName.LOCK, writer.AddToBody(Lock).IndirectReference);
  96.             field.Flags = PdfAnnotation.FLAGS_PRINT;
  97.             cell.CellEvent = new MySignatureFieldEvent(field);
  98.             return cell;
  99.         }
  100.        
  101.         public void Certify(String keystore, String src, String name, String dest) {
  102.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  103.             String alias = "";
  104.             ICollection chain = new List();
  105.             // searching for private key
  106.             foreach (string al in store.Aliases)
  107.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  108.                     alias = al;
  109.                     break;
  110.                 }
  111.             AsymmetricKeyEntry pk = store.GetKey(alias);
  112.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  113.                 chain.Add(c.Certificate);
  114.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  115.  
  116.             PdfReader reader = new PdfReader(src);
  117.             FileStream os = new FileStream(dest, FileMode.Create);
  118.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  119.             // Creating the appearance
  120.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  121.             appearance.SetVisibleSignature(name);
  122.             appearance.CertificationLevel = PdfSignatureAppearance.CERTIFIED_FORM_FILLING;
  123.             AcroFields form = stamper.AcroFields;
  124.             form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  125.             // Creating the signature
  126.             PrivateKeySignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
  127.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  128.         }
  129.        
  130.         public void FillOutAndSign(String keystore, String src, String name, String fname, String value, String dest) {
  131.             Pkcs12Store store = new Pkcs12Store(new FileStream(keystore, FileMode.Open), PASSWORD);
  132.             String alias = "";
  133.             ICollection chain = new List();
  134.             // searching for private key
  135.             foreach (string al in store.Aliases)
  136.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  137.                     alias = al;
  138.                     break;
  139.                 }
  140.             AsymmetricKeyEntry pk = store.GetKey(alias);
  141.             foreach (X509CertificateEntry c in store.GetCertificateChain(alias))
  142.                 chain.Add(c.Certificate);
  143.             RsaPrivateCrtKeyParameters parameters = pk.Key as RsaPrivateCrtKeyParameters;
  144.  
  145.             PdfReader reader = new PdfReader(src);
  146.             FileStream os = new FileStream(dest, FileMode.Create);
  147.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0', null, true);
  148.             AcroFields form = stamper.AcroFields;
  149.             form.SetField(fname, value);
  150.             form.SetFieldProperty(name, "setfflags", PdfFormField.FF_READ_ONLY, null);
  151.             form.SetFieldProperty(fname, "setfflags", PdfFormField.FF_READ_ONLY, null);
  152.             // Creating the appearance
  153.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  154.             appearance.SetVisibleSignature(name);
  155.             // Creating the signature
  156.             PrivateKeySignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
  157.             MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);
  158.         }
  159.        
  160.         public void FillOut(String src, String dest, String name, String value) {
  161.             PdfReader reader = new PdfReader(src);
  162.             PdfStamper stamper = new PdfStamper(reader, new FileStream(dest, FileMode.Create), '\0', true);
  163.             AcroFields form = stamper.AcroFields;
  164.             form.SetField(name, value);
  165.             stamper.Close();
  166.         }
  167.        
  168.         public static void Main(String[] args) {
  169.             C2_12_LockFields app = new C2_12_LockFields();
  170.             app.CreateForm();
  171.             app.Certify(ALICE, FORM, "sig1", String.Format(DEST, 1, "alice"));
  172.             app.FillOutAndSign(BOB, String.Format(DEST, 1, "alice"), "sig2", "approved_bob", "Read and Approved by Bob", String.Format(DEST, 2, "alice_and_bob"));
  173.             app.FillOutAndSign(CAROL, String.Format(DEST, 2, "alice_and_bob"), "sig3", "approved_carol", "Read and Approved by Carol", String.Format(DEST, 3, "alice_bob_and_carol"));
  174.             app.FillOutAndSign(DAVE, String.Format(DEST, 3, "alice_bob_and_carol"), "sig4", "approved_dave", "Read and Approved by Dave", String.Format(DEST, 4, "alice_bob_carol_and_dave"));
  175.             app.FillOut(String.Format(DEST, 2, "alice_and_bob"), String.Format(DEST, 5, "alice_and_bob_broken_by_chuck"), "approved_bob", "Changed by Chuck");
  176.             app.FillOut(String.Format(DEST, 4, "alice_bob_carol_and_dave"), String.Format(DEST, 6, "dave_broken_by_chuck"), "approved_carol", "Changed by Chuck");
  177.         }
  178.     }
  179. }
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