Digital signatures - chapter 4

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

1st November 2015
admin-marketing

Switch code for this example

C4_01_SignWithPKCS11HSM.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.security.GeneralSecurityException;
  7. import java.security.KeyStore;
  8. import java.security.PrivateKey;
  9. import java.security.Provider;
  10. import java.security.Security;
  11. import java.security.cert.Certificate;
  12. import java.security.cert.X509Certificate;
  13. import java.util.ArrayList;
  14. import java.util.Collection;
  15. import java.util.List;
  16. import java.util.Properties;
  17.  
  18. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  19.  
  20. import sun.security.pkcs11.SunPKCS11;
  21.  
  22. import com.itextpdf.text.DocumentException;
  23. import com.itextpdf.text.Rectangle;
  24. import com.itextpdf.text.log.LoggerFactory;
  25. import com.itextpdf.text.log.SysoLogger;
  26. import com.itextpdf.text.pdf.PdfReader;
  27. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  28. import com.itextpdf.text.pdf.PdfStamper;
  29. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  30. import com.itextpdf.text.pdf.security.CertificateUtil;
  31. import com.itextpdf.text.pdf.security.CrlClient;
  32. import com.itextpdf.text.pdf.security.CrlClientOnline;
  33. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  34. import com.itextpdf.text.pdf.security.ExternalDigest;
  35. import com.itextpdf.text.pdf.security.ExternalSignature;
  36. import com.itextpdf.text.pdf.security.MakeSignature;
  37. import com.itextpdf.text.pdf.security.OcspClient;
  38. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  39. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  40. import com.itextpdf.text.pdf.security.TSAClient;
  41. import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
  42. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  43.  
  44. public class C4_01_SignWithPKCS11HSM {
  45.    
  46.     public static final String SRC = "/home/itext/hello.pdf";
  47.     public static final String PROPS = "/home/itext/key.properties";
  48.     public static final String DEST = "/home/itext/hello_hsm.pdf";
  49.  
  50.     public void sign(String src, String dest,
  51.             Certificate[] chain, PrivateKey pk,
  52.             String digestAlgorithm, String provider, CryptoStandard subfilter,
  53.             String reason, String location,
  54.             Collection crlList,
  55.             OcspClient ocspClient,
  56.             TSAClient tsaClient,
  57.             int estimatedSize)
  58.                     throws GeneralSecurityException, IOException, DocumentException {
  59.         // Creating the reader and the stamper
  60.         PdfReader reader = new PdfReader(src);
  61.         FileOutputStream os = new FileOutputStream(dest);
  62.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  63.         // Creating the appearance
  64.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  65.         appearance.setReason(reason);
  66.         appearance.setLocation(location);
  67.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  68.         // Creating the signature
  69.         ExternalSignature pks = new PrivateKeySignature(pk, digestAlgorithm, provider);
  70.         ExternalDigest digest = new BouncyCastleDigest();
  71.         MakeSignature.signDetached(appearance, digest, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
  72.     }
  73.    
  74.     public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException {
  75.  
  76.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  77.        
  78.         Properties properties = new Properties();
  79.         properties.load(new FileInputStream(PROPS));
  80.         char[] pass = properties.getProperty("PASSWORD").toCharArray();
  81.         String pkcs11cfg = properties.getProperty("PKCS11CFG");
  82.  
  83.         BouncyCastleProvider providerBC = new BouncyCastleProvider();
  84.         Security.addProvider(providerBC);
  85.         FileInputStream fis = new FileInputStream(pkcs11cfg);
  86.         Provider providerPKCS11 = new SunPKCS11(fis);
  87.         Security.addProvider(providerPKCS11);
  88.        
  89.         KeyStore ks = KeyStore.getInstance("PKCS11");
  90.         ks.load(null, pass);
  91.         String alias = (String)ks.aliases().nextElement();
  92.         PrivateKey pk = (PrivateKey)ks.getKey(alias, pass);
  93.         Certificate[] chain = ks.getCertificateChain(alias);
  94.         OcspClient ocspClient = new OcspClientBouncyCastle();
  95.         TSAClient tsaClient = null;
  96.         for (int i = 0; i < chain.length; i++) {
  97.             X509Certificate cert = (X509Certificate)chain[i];
  98.             String tsaUrl = CertificateUtil.getTSAURL(cert);
  99.             if (tsaUrl != null) {
  100.                 tsaClient = new TSAClientBouncyCastle(tsaUrl);
  101.                 break;
  102.             }
  103.         }
  104.         List crlList = new ArrayList();
  105.         crlList.add(new CrlClientOnline(chain));
  106.         C4_01_SignWithPKCS11HSM app = new C4_01_SignWithPKCS11HSM();
  107.         app.sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, providerPKCS11.getName(), CryptoStandard.CMS,
  108.                 "HSM test", "Ghent", crlList, ocspClient, tsaClient, 0);
  109.     }
  110. }
C4_02_SignWithPKCS11USB.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.chapter4;
  9.  
  10. import java.io.ByteArrayInputStream;
  11. import java.io.FileInputStream;
  12. import java.io.IOException;
  13. import java.security.GeneralSecurityException;
  14. import java.security.KeyStore;
  15. import java.security.PrivateKey;
  16. import java.security.Provider;
  17. import java.security.Security;
  18. import java.security.cert.Certificate;
  19. import java.security.cert.X509Certificate;
  20. import java.util.ArrayList;
  21. import java.util.List;
  22. import java.util.Properties;
  23.  
  24. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  25.  
  26. import sun.security.pkcs11.SunPKCS11;
  27. import sun.security.pkcs11.wrapper.CK_C_INITIALIZE_ARGS;
  28. import sun.security.pkcs11.wrapper.CK_TOKEN_INFO;
  29. import sun.security.pkcs11.wrapper.PKCS11;
  30. import sun.security.pkcs11.wrapper.PKCS11Exception;
  31.  
  32. import com.itextpdf.text.DocumentException;
  33. import com.itextpdf.text.log.LoggerFactory;
  34. import com.itextpdf.text.log.SysoLogger;
  35. import com.itextpdf.text.pdf.security.CertificateUtil;
  36. import com.itextpdf.text.pdf.security.CrlClient;
  37. import com.itextpdf.text.pdf.security.CrlClientOnline;
  38. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  39. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  40. import com.itextpdf.text.pdf.security.OcspClient;
  41. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  42. import com.itextpdf.text.pdf.security.TSAClient;
  43. import com.itextpdf.text.pdf.security.TSAClientBouncyCastle;
  44.  
  45. public class C4_02_SignWithPKCS11USB extends C4_01_SignWithPKCS11HSM {
  46.     public static final String SRC = "src/main/resources/hello.pdf";
  47.     public static final String DEST = "results/chapter4/hello_token.pdf";
  48.     public static final String DLL = "c:/windows/system32/dkck201.dll";
  49.  
  50.     public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException {
  51.  
  52.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  53.        
  54.         Properties properties = new Properties();
  55.         properties.load(new FileInputStream("c:/home/blowagie/key.properties"));
  56.         char[] pass = properties.getProperty("PASSWORD").toCharArray();
  57.  
  58.         String config = "name=ikey4000\n" +
  59.                 "library=" + DLL + "\n" +
  60.                 "slotListIndex = " + getSlotsWithTokens(DLL)[0];
  61.         ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
  62.         Provider providerPKCS11 = new SunPKCS11(bais);
  63.         Security.addProvider(providerPKCS11);
  64.         System.out.println(providerPKCS11.getName());
  65.         BouncyCastleProvider providerBC = new BouncyCastleProvider();
  66.         Security.addProvider(providerBC);
  67.        
  68.         KeyStore ks = KeyStore.getInstance("PKCS11");
  69.         ks.load(null, pass);
  70.         String alias = (String)ks.aliases().nextElement();
  71.         PrivateKey pk = (PrivateKey)ks.getKey(alias, pass);
  72.         Certificate[] chain = ks.getCertificateChain(alias);
  73.         OcspClient ocspClient = new OcspClientBouncyCastle();
  74.         TSAClient tsaClient = null;
  75.         for (int i = 0; i < chain.length; i++) {
  76.             X509Certificate cert = (X509Certificate)chain[i];
  77.             String tsaUrl = CertificateUtil.getTSAURL(cert);
  78.             if (tsaUrl != null) {
  79.                 tsaClient = new TSAClientBouncyCastle(tsaUrl);
  80.                 break;
  81.             }
  82.         }
  83.         List crlList = new ArrayList();
  84.         crlList.add(new CrlClientOnline(chain));
  85.         C4_02_SignWithPKCS11USB app = new C4_02_SignWithPKCS11USB();
  86.         app.sign(SRC, DEST, chain, pk, DigestAlgorithms.SHA256, providerPKCS11.getName(), CryptoStandard.CMS,
  87.                 "Test", "Ghent", crlList, ocspClient, tsaClient, 0);
  88.     }
  89.    
  90.    
  91.     public static long[] getSlotsWithTokens(String libraryPath) throws IOException{
  92.         CK_C_INITIALIZE_ARGS initArgs = new CK_C_INITIALIZE_ARGS();
  93.         String functionList = "C_GetFunctionList";
  94.  
  95.         initArgs.flags = 0;
  96.         PKCS11 tmpPKCS11 = null;
  97.         long[] slotList = null;
  98.         try {
  99.             try {
  100.                 tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, false);
  101.             } catch (IOException ex) {
  102.                 ex.printStackTrace();
  103.                 throw ex;
  104.             }
  105.         } catch (PKCS11Exception e) {
  106.             try {
  107.                 initArgs = null;
  108.                 tmpPKCS11 = PKCS11.getInstance(libraryPath, functionList, initArgs, true);
  109.             } catch (IOException ex) {
  110.                ex.printStackTrace();
  111.             } catch (PKCS11Exception ex) {
  112.                ex.printStackTrace();
  113.             }
  114.         }
  115.  
  116.         try {
  117.             slotList = tmpPKCS11.C_GetSlotList(true);
  118.  
  119.             for (long slot : slotList){
  120.                 CK_TOKEN_INFO tokenInfo = tmpPKCS11.C_GetTokenInfo(slot);
  121.                 System.out.println("slot: "+slot+"\nmanufacturerID: "
  122.                         + String.valueOf(tokenInfo.manufacturerID) + "\nmodel: "
  123.                         + String.valueOf(tokenInfo.model));
  124.             }
  125.         } catch (PKCS11Exception ex) {
  126.                 ex.printStackTrace();
  127.         } catch (Throwable t) {
  128.             t.printStackTrace();
  129.         }
  130.  
  131.         return slotList;
  132.  
  133.     }
  134. }
C4_03_SignWithPKCS11SC.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.chapter4;
  9.  
  10. import java.io.ByteArrayInputStream;
  11. import java.io.IOException;
  12. import java.security.GeneralSecurityException;
  13. import java.security.KeyStore;
  14. import java.security.PrivateKey;
  15. import java.security.Provider;
  16. import java.security.Security;
  17. import java.security.cert.Certificate;
  18. import java.util.ArrayList;
  19. import java.util.Enumeration;
  20. import java.util.List;
  21.  
  22. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  23.  
  24. import sun.security.pkcs11.SunPKCS11;
  25.  
  26. import com.itextpdf.text.DocumentException;
  27. import com.itextpdf.text.log.LoggerFactory;
  28. import com.itextpdf.text.log.SysoLogger;
  29. import com.itextpdf.text.pdf.security.CrlClient;
  30. import com.itextpdf.text.pdf.security.CrlClientOnline;
  31. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  32. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  33. import com.itextpdf.text.pdf.security.OcspClient;
  34. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  35.  
  36. public class C4_03_SignWithPKCS11SC extends C4_02_SignWithPKCS11USB {
  37.     public static final String SRC = "src/main/resources/hello.pdf";
  38.     public static final String DEST = "results/chapter4/hello_smartcard_%s.pdf";
  39.     public static final String DLL = "c:/windows/system32/beidpkcs11.dll";
  40.  
  41.     public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException {
  42.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  43.         String config = "name=beid\n" +
  44.                 "library=" + DLL + "\n" +
  45.                 "slotListIndex = " + getSlotsWithTokens(DLL)[0];
  46.         ByteArrayInputStream bais = new ByteArrayInputStream(config.getBytes());
  47.         Provider providerPKCS11 = new SunPKCS11(bais);
  48.         Security.addProvider(providerPKCS11);
  49.         BouncyCastleProvider providerBC = new BouncyCastleProvider();
  50.         Security.addProvider(providerBC);
  51.         KeyStore ks = KeyStore.getInstance("PKCS11");
  52.         ks.load(null, null);
  53.         Enumeration aliases = ks.aliases();
  54.         while (aliases.hasMoreElements()) {
  55.             System.out.println(aliases.nextElement());
  56.         }
  57.         smartcardsign(providerPKCS11.getName(), ks, "Authentication");
  58.         smartcardsign(providerPKCS11.getName(), ks, "Signature");
  59.     }
  60.     public static void smartcardsign(String provider, KeyStore ks, String alias) throws GeneralSecurityException, IOException, DocumentException {
  61.         PrivateKey pk = (PrivateKey)ks.getKey(alias, null);
  62.         Certificate[] chain = ks.getCertificateChain(alias);
  63.         OcspClient ocspClient = new OcspClientBouncyCastle();
  64.         List crlList = new ArrayList();
  65.         crlList.add(new CrlClientOnline(chain));
  66.         C4_03_SignWithPKCS11SC app = new C4_03_SignWithPKCS11SC();
  67.         app.sign(SRC, String.format(DEST, alias), chain, pk, DigestAlgorithms.SHA256, provider, CryptoStandard.CMS,
  68.                 "Test", "Ghent", crlList, ocspClient, null, 0);
  69.     }
  70. }
C4_04_InspectBEID.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5.  
  6. import javax.smartcardio.CardException;
  7. import javax.smartcardio.CardTerminal;
  8.  
  9. import com.itextpdf.smartcard.CardReaders;
  10. import com.itextpdf.smartcard.SmartCard;
  11. import com.itextpdf.smartcard.beid.BeIDFileFactory;
  12. import com.itextpdf.smartcard.beid.pojos.AddressPojo;
  13. import com.itextpdf.smartcard.beid.pojos.IdentityPojo;
  14. import com.itextpdf.smartcard.beid.pojos.PhotoPojo;
  15.  
  16. public class C4_04_InspectBEID {
  17.  
  18.     public static final String PHOTO = "results/chapter4/photo.jpg";
  19.    
  20.     public static void main(String[] args) throws CardException, IOException {
  21.         CardReaders readers = new CardReaders();
  22.         for (CardTerminal terminal : readers.getReaders()) {
  23.             System.out.println(terminal.getName());
  24.         }
  25.         for (CardTerminal terminal : readers.getReadersWithCard()) {
  26.             System.out.println(terminal.getName());
  27.             SmartCard card = new SmartCard(terminal);
  28.             IdentityPojo id = BeIDFileFactory.getIdentity(card);
  29.             System.out.println(id.toString());
  30.             AddressPojo address = BeIDFileFactory.getAddress(card);
  31.             System.out.println(address);
  32.             PhotoPojo photo = BeIDFileFactory.getPhoto(card);
  33.             FileOutputStream fos = new FileOutputStream(PHOTO);
  34.             fos.write(photo.getPhoto());
  35.             fos.flush();
  36.             fos.close();
  37.         }
  38.     }
  39. }
C4_05_SignWithBEID.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.IOException;
  4. import java.security.GeneralSecurityException;
  5. import java.security.cert.X509Certificate;
  6.  
  7. import javax.crypto.Cipher;
  8. import javax.smartcardio.CardException;
  9. import javax.smartcardio.CardTerminal;
  10.  
  11. import com.itextpdf.smartcard.CardReaders;
  12. import com.itextpdf.smartcard.PinDialog;
  13. import com.itextpdf.smartcard.SmartCardWithKey;
  14. import com.itextpdf.smartcard.beid.BeIDCertificates;
  15.  
  16. public class C4_05_SignWithBEID {
  17.  
  18.     public static void main(String[] args) throws CardException, IOException, GeneralSecurityException {
  19.         CardReaders readers = new CardReaders();
  20.         for (CardTerminal terminal : readers.getReadersWithCard()) {
  21.             SmartCardWithKey card = new SmartCardWithKey(terminal, BeIDCertificates.AUTHENTICATION_KEY_ID, "RSA");
  22.             card.setPinProvider(new PinDialog(4));
  23.             byte[] signed = card.sign("ABCD".getBytes(), "SHA-256");
  24.             System.out.println(new String(signed));
  25.             X509Certificate cert = card.readCertificate(BeIDCertificates.AUTHN_CERT_FILE_ID);
  26.             Cipher cipher = Cipher.getInstance("RSA");
  27.             cipher.init(Cipher.DECRYPT_MODE, cert.getPublicKey());
  28.             System.out.println(new String(cipher.doFinal(signed)));
  29.         }
  30.     }
  31. }
C4_06_SignWithBEID.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.security.GeneralSecurityException;
  6. import java.security.Security;
  7. import java.security.cert.Certificate;
  8. import java.util.ArrayList;
  9. import java.util.Collection;
  10.  
  11. import javax.smartcardio.CardException;
  12.  
  13. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  14.  
  15. import com.itextpdf.smartcard.CardReaders;
  16. import com.itextpdf.smartcard.EidSignature;
  17. import com.itextpdf.smartcard.SmartCardWithKey;
  18. import com.itextpdf.smartcard.beid.BeIDCard;
  19. import com.itextpdf.smartcard.beid.BeIDCertificates;
  20. import com.itextpdf.text.DocumentException;
  21. import com.itextpdf.text.Rectangle;
  22. import com.itextpdf.text.log.LoggerFactory;
  23. import com.itextpdf.text.log.SysoLogger;
  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.CrlClient;
  29. import com.itextpdf.text.pdf.security.CrlClientOnline;
  30. import com.itextpdf.text.pdf.security.ExternalDigest;
  31. import com.itextpdf.text.pdf.security.ExternalSignature;
  32. import com.itextpdf.text.pdf.security.MakeSignature;
  33. import com.itextpdf.text.pdf.security.OcspClient;
  34. import com.itextpdf.text.pdf.security.OcspClientBouncyCastle;
  35. import com.itextpdf.text.pdf.security.TSAClient;
  36. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  37.  
  38. public class C4_06_SignWithBEID {
  39.  
  40.     public static final String SRC = "src/main/resources/hello.pdf";
  41.     public static final String DEST = "results/chapter4/hello_beid.pdf";
  42.  
  43.     public void sign(String src, String dest,
  44.             SmartCardWithKey card, Certificate[] chain,
  45.             CryptoStandard subfilter,
  46.             String reason, String location,
  47.             Collection crlList,
  48.             OcspClient ocspClient,
  49.             TSAClient tsaClient,
  50.             int estimatedSize)
  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(new Rectangle(36, 748, 144, 780), 1, "sig");
  61.         // Creating the signature
  62.         ExternalSignature eid = new EidSignature(card, "SHA256", "BC");
  63.         ExternalDigest digest = new BouncyCastleDigest();
  64.         MakeSignature.signDetached(appearance, digest, eid, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
  65.     }
  66.    
  67.     public static void main(String[] args) throws CardException, GeneralSecurityException, IOException, DocumentException {
  68.         LoggerFactory.getInstance().setLogger(new SysoLogger());
  69.        
  70.         BouncyCastleProvider provider = new BouncyCastleProvider();
  71.         Security.addProvider(provider);
  72.        
  73.         CardReaders readers = new CardReaders();
  74.         SmartCardWithKey card = new BeIDCard(readers.getReadersWithCard().get(0));
  75.         card.setSecure(true);
  76.         Certificate[] chain = BeIDCertificates.getSignCertificateChain(card);
  77.         Collection crlList = new ArrayList();
  78.         crlList.add(new CrlClientOnline(chain));
  79.         OcspClient ocspClient = new OcspClientBouncyCastle();
  80.         C4_06_SignWithBEID app = new C4_06_SignWithBEID();
  81.         app.sign(SRC, DEST, card, chain, CryptoStandard.CMS,
  82.                 "Test", "Ghent", crlList, ocspClient, null, 0);
  83.     }
  84. }
C4_07_ClientServerSigning.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.net.HttpURLConnection;
  9. import java.net.URL;
  10. import java.security.GeneralSecurityException;
  11. import java.security.cert.Certificate;
  12. import java.security.cert.CertificateFactory;
  13.  
  14. import com.itextpdf.text.DocumentException;
  15. import com.itextpdf.text.ExceptionConverter;
  16. import com.itextpdf.text.Rectangle;
  17. import com.itextpdf.text.pdf.PdfReader;
  18. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  19. import com.itextpdf.text.pdf.PdfStamper;
  20. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  21. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  22. import com.itextpdf.text.pdf.security.ExternalDigest;
  23. import com.itextpdf.text.pdf.security.ExternalSignature;
  24. import com.itextpdf.text.pdf.security.MakeSignature;
  25. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  26.  
  27. public class C4_07_ClientServerSigning {
  28.  
  29.     public static final String SRC = "src/main/resources/hello.pdf";
  30.     public static final String DEST = "results/chapter4/hello_server.pdf";
  31.  
  32.     public static final String CERT = "http://demo.itextsupport.com/SigningApp/itextpdf.cer";
  33.    
  34.     public class ServerSignature implements ExternalSignature {
  35.         public static final String SIGN = "http://demo.itextsupport.com/SigningApp/signbytes";
  36.        
  37.         public String getHashAlgorithm() {
  38.             return DigestAlgorithms.SHA256;
  39.         }
  40.  
  41.         public String getEncryptionAlgorithm() {
  42.             return "RSA";
  43.         }
  44.  
  45.         public byte[] sign(byte[] message) throws GeneralSecurityException {
  46.             try {
  47.                 URL url = new URL(SIGN);
  48.                 HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  49.                 conn.setDoOutput(true);
  50.                 conn.setRequestMethod("POST");
  51.                 conn.connect();
  52.                 OutputStream os = conn.getOutputStream();
  53.                 os.write(message);
  54.                 os.flush();
  55.                 os.close();
  56.                 InputStream is = conn.getInputStream();
  57.                 ByteArrayOutputStream baos = new ByteArrayOutputStream();
  58.                 byte[] b = new byte[1];  
  59.                 int read;  
  60.                 while ((read = is.read(b)) != -1) {  
  61.                     baos.write(b, 0, read);  
  62.                 }
  63.                 is.close();
  64.                 return baos.toByteArray();
  65.             } catch (IOException e) {
  66.                 throw new ExceptionConverter(e);
  67.             }
  68.         }
  69.        
  70.     }
  71.    
  72.     public void sign(String src, String dest,
  73.             Certificate[] chain,
  74.             CryptoStandard subfilter,
  75.             String reason, String location)
  76.                     throws GeneralSecurityException, IOException, DocumentException {
  77.         // Creating the reader and the stamper
  78.         PdfReader reader = new PdfReader(src);
  79.         FileOutputStream os = new FileOutputStream(dest);
  80.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  81.         // Creating the appearance
  82.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  83.         appearance.setReason(reason);
  84.         appearance.setLocation(location);
  85.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  86.         // Creating the signature
  87.         ExternalDigest digest = new BouncyCastleDigest();
  88.         ExternalSignature signature = new ServerSignature();
  89.         MakeSignature.signDetached(appearance, digest, signature, chain, null, null, null, 0, subfilter);
  90.     }
  91.    
  92.     public static void main(String[] args) throws GeneralSecurityException, IOException, DocumentException {
  93.         CertificateFactory factory = CertificateFactory.getInstance("X.509");
  94.         URL certUrl = new URL(CERT);
  95.         Certificate[] chain = new Certificate[1];
  96.         chain[0] = factory.generateCertificate(certUrl.openStream());
  97.         C4_07_ClientServerSigning app = new C4_07_ClientServerSigning();
  98.         app.sign(SRC, DEST, chain, CryptoStandard.CMS, "Test", "Ghent");
  99.     }
  100. }
C4_08_ServerClientSigning.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.FileInputStream;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.HttpURLConnection;
  10. import java.net.URL;
  11. import java.security.GeneralSecurityException;
  12. import java.security.KeyStore;
  13. import java.security.PrivateKey;
  14. import java.security.Signature;
  15. import java.util.List;
  16.  
  17. public class C4_08_ServerClientSigning {
  18.  
  19.     public static final String CERT = "src/main/resources/bruno.crt";
  20.     public static final String KEYSTORE = "src/main/resources/ks";
  21.     public static final char[] PASSWORD = "password".toCharArray();
  22.     public static final String DEST = "results/chapter4/hello_server2.pdf";
  23.  
  24.     public static final String PRE = "http://demo.itextsupport.com/SigningApp/presign";
  25.     public static final String POST = "http://demo.itextsupport.com/SigningApp/postsign";
  26.    
  27.     public static void main(String[] args) throws IOException, GeneralSecurityException {
  28.         // we make a connection to a PreSign servlet
  29.         URL url = new URL(PRE);
  30.         HttpURLConnection conn = (HttpURLConnection)url.openConnection();
  31.         conn.setDoOutput(true);
  32.         conn.setRequestMethod("POST");
  33.         conn.connect();
  34.         // we upload our self-signed certificate
  35.         OutputStream os = conn.getOutputStream();
  36.         FileInputStream fis = new FileInputStream(CERT);
  37.         int read;
  38.         byte[] data = new byte[256];
  39.         while ((read = fis.read(data, 0, data.length)) != -1) {
  40.             os.write(data, 0, read);
  41.         }
  42.         os.flush();
  43.         os.close();
  44.         // we use cookies to maintain a session
  45.         List cookies = conn.getHeaderFields().get("Set-Cookie");
  46.         // we receive a hash that needs to be signed
  47.         InputStream is = conn.getInputStream();
  48.         ByteArrayOutputStream baos = new ByteArrayOutputStream();
  49.         data = new byte[256];
  50.         while ((read = is.read(data)) != -1) {  
  51.             baos.write(data, 0, read);  
  52.         }
  53.         is.close();
  54.         byte[] hash = baos.toByteArray();
  55.        
  56.         // we load our private key from the key store
  57.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  58.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  59.         String alias = (String)ks.aliases().nextElement();
  60.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  61.         // we sign the hash received from the server
  62.         Signature sig = Signature.getInstance("SHA256withRSA");
  63.         sig.initSign(pk);
  64.         sig.update(hash);
  65.         data = sig.sign();
  66.        
  67.         // we make a connection to the PostSign Servlet
  68.         url = new URL(POST);
  69.         conn = (HttpURLConnection)url.openConnection();
  70.         for (String cookie : cookies) {
  71.             conn.addRequestProperty("Cookie", cookie.split(";", 2)[0]);
  72.         }
  73.         conn.setDoOutput(true);
  74.         conn.setRequestMethod("POST");
  75.         conn.connect();
  76.         // we upload the signed bytes
  77.         os = conn.getOutputStream();
  78.         os.write(data);
  79.         os.flush();
  80.         os.close();
  81.         // we receive the signed document
  82.         is = conn.getInputStream();
  83.         FileOutputStream fos = new FileOutputStream(DEST);
  84.         data = new byte[256];
  85.         while ((read = is.read(data)) != -1) {  
  86.             fos.write(data, 0, read);  
  87.         }
  88.         is.close();
  89.         fos.flush();
  90.         fos.close();
  91.     }
  92. }
C4_09_DeferredSigning.java
  1. package signatures.chapter4;
  2.  
  3. import java.io.FileInputStream;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.security.GeneralSecurityException;
  8. import java.security.KeyStore;
  9. import java.security.PrivateKey;
  10. import java.security.Security;
  11. import java.security.cert.Certificate;
  12. import java.util.Calendar;
  13.  
  14. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  15.  
  16. import com.itextpdf.text.DocumentException;
  17. import com.itextpdf.text.ExceptionConverter;
  18. import com.itextpdf.text.Rectangle;
  19. import com.itextpdf.text.pdf.PdfDictionary;
  20. import com.itextpdf.text.pdf.PdfName;
  21. import com.itextpdf.text.pdf.PdfReader;
  22. import com.itextpdf.text.pdf.PdfSignatureAppearance;
  23. import com.itextpdf.text.pdf.PdfStamper;
  24. import com.itextpdf.text.pdf.security.BouncyCastleDigest;
  25. import com.itextpdf.text.pdf.security.DigestAlgorithms;
  26. import com.itextpdf.text.pdf.security.ExternalBlankSignatureContainer;
  27. import com.itextpdf.text.pdf.security.ExternalSignatureContainer;
  28. import com.itextpdf.text.pdf.security.MakeSignature;
  29. import com.itextpdf.text.pdf.security.MakeSignature.CryptoStandard;
  30. import com.itextpdf.text.pdf.security.PdfPKCS7;
  31. import com.itextpdf.text.pdf.security.PrivateKeySignature;
  32.  
  33. public class C4_09_DeferredSigning {
  34.     public static final String CERT = "src/main/resources/bruno.crt";
  35.     public static final String KEYSTORE = "src/main/resources/ks";
  36.     public static final char[] PASSWORD = "password".toCharArray();
  37.    
  38.     public static final String SRC = "src/main/resources/hello.pdf";
  39.     public static final String TEMP = "results/chapter4/hello_empty_sig.pdf";
  40.     public static final String DEST = "results/chapter4/hello_sig_ok.pdf";
  41.  
  42.     class MyExternalSignatureContainer implements ExternalSignatureContainer {
  43.  
  44.         protected PrivateKey pk;
  45.         protected Certificate[] chain;
  46.        
  47.         public MyExternalSignatureContainer(PrivateKey pk, Certificate[] chain) {
  48.             this.pk = pk;
  49.             this.chain = chain;
  50.         }
  51.        
  52.         public byte[] sign(InputStream is) throws GeneralSecurityException {
  53.             try {
  54.                 PrivateKeySignature signature = new PrivateKeySignature(pk, "SHA256", "BC");
  55.                 String hashAlgorithm = signature.getHashAlgorithm();
  56.                 BouncyCastleDigest digest = new BouncyCastleDigest();
  57.                 PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);
  58.                 byte hash[] = DigestAlgorithms.digest(is, digest.getMessageDigest(hashAlgorithm));
  59.                 Calendar cal = Calendar.getInstance();
  60.                 byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, cal, null, null, CryptoStandard.CMS);
  61.                 byte[] extSignature = signature.sign(sh);
  62.                 sgn.setExternalDigest(extSignature, null, signature.getEncryptionAlgorithm());
  63.                 return sgn.getEncodedPKCS7(hash, cal, null, null, null, CryptoStandard.CMS);
  64.             }
  65.             catch (IOException ioe) {
  66.                 throw new ExceptionConverter(ioe);
  67.             }
  68.         }
  69.  
  70.         public void modifySigningDictionary(PdfDictionary signDic) {
  71.         }
  72.        
  73.     }
  74.    
  75.     public void emptySignature(String src, String dest, String fieldname, Certificate[] chain) throws IOException, DocumentException, GeneralSecurityException {
  76.         PdfReader reader = new PdfReader(src);
  77.         FileOutputStream os = new FileOutputStream(dest);
  78.         PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
  79.         PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
  80.         appearance.setVisibleSignature(new Rectangle(36, 748, 144, 780), 1, fieldname);
  81.         appearance.setCertificate(chain[0]);
  82.         ExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
  83.         MakeSignature.signExternalContainer(appearance, external, 8192);
  84.     }
  85.    
  86.     public void createSignature(String src, String dest, String fieldname, PrivateKey pk, Certificate[] chain) throws IOException, DocumentException, GeneralSecurityException {
  87.        
  88.         PdfReader reader = new PdfReader(src);
  89.         FileOutputStream os = new FileOutputStream(dest);
  90.         ExternalSignatureContainer external = new MyExternalSignatureContainer(pk, chain);
  91.         MakeSignature.signDeferred(reader, fieldname, os, external);
  92.     }
  93.    
  94.     public static void main(String[] args) throws IOException, GeneralSecurityException, DocumentException {
  95.         BouncyCastleProvider providerBC = new BouncyCastleProvider();
  96.         Security.addProvider(providerBC);
  97.  
  98.         // we load our private key from the key store
  99.         KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
  100.         ks.load(new FileInputStream(KEYSTORE), PASSWORD);
  101.         String alias = (String)ks.aliases().nextElement();
  102.         Certificate[] chain = ks.getCertificateChain(alias);
  103.         PrivateKey pk = (PrivateKey) ks.getKey(alias, PASSWORD);
  104.        
  105.         C4_09_DeferredSigning app = new C4_09_DeferredSigning();
  106.         app.emptySignature(SRC, TEMP, "sig", chain);
  107.         app.createSignature(TEMP, DEST, "sig", pk, chain);
  108.     }
  109. }
C4_03_SignWithPKCS11SC.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Security.Cryptography.X509Certificates;
  13. using Cryptware.NCryptoki;
  14. using Org.BouncyCastle.Security;
  15. using iTextSharp.text;
  16. using iTextSharp.text.log;
  17. using iTextSharp.text.pdf;
  18. using iTextSharp.text.pdf.security;
  19. using X509Certificate = Org.BouncyCastle.X509.X509Certificate;
  20.  
  21. namespace signatures.chapter4 {
  22.     class CryptokiPrivateKeySignature : IExternalSignature
  23.     {
  24.         private readonly Session session;
  25.         RSAPrivateKey privateKey;
  26.  
  27.         public CryptokiPrivateKeySignature(Session session, String alias) {
  28.             this.session = session;
  29.             CryptokiCollection template = new CryptokiCollection();
  30.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_PRIVATE_KEY));
  31.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_KEY_TYPE, Key.CKK_RSA));
  32.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias));
  33.             privateKey = (RSAPrivateKey)session.Objects.Find(template);
  34.         }
  35.  
  36.         public String GetHashAlgorithm() {
  37.             return "SHA1";
  38.         }
  39.        
  40.         public String GetEncryptionAlgorithm() {
  41.             return "RSA";
  42.         }
  43.  
  44.         public byte[] Sign(byte[] message) {
  45.             session.SignInit(Mechanism.SHA1_RSA_PKCS, privateKey);
  46.             return session.Sign(message);
  47.         }
  48.     }
  49.  
  50.     class C4_03_SignWithPKCS11SC {
  51.         public const String SRC = "../../../../resources/hello.pdf";
  52.         public const String DEST = "../../../../results/chapter4/hello_smartcard_{0}.pdf";
  53.         public const String DLL = "c:/windows/system32/beidpkcs11.dll";
  54.  
  55.         public void Sign(String src, String dest, ICollection chain, Session session, String alias,
  56.                          String digestAlgorithm, CryptoStandard subfilter, String reason, String location,
  57.                          ICollection crlList, IOcspClient ocspClient, ITSAClient tsaClient, int estimatedSize) {
  58.             // Creating the reader and the stamper
  59.             PdfReader reader = null;
  60.             PdfStamper stamper = null;
  61.             FileStream os = null;
  62.             try {
  63.                 reader = new PdfReader(src);
  64.                 os = new FileStream(dest, FileMode.Create);
  65.                 stamper = PdfStamper.CreateSignature(reader, os, '\0');
  66.                 // Creating the appearance
  67.                 PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  68.                 appearance.Reason = reason;
  69.                 appearance.Location = location;
  70.                 appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  71.                 // Creating the signature
  72.                 IExternalSignature pks = new CryptokiPrivateKeySignature(session, alias);
  73.                 MakeSignature.SignDetached(appearance, pks, chain, crlList, ocspClient, tsaClient, estimatedSize, subfilter);
  74.             } finally {
  75.                 if (reader != null)
  76.                     reader.Close();
  77.                 if (stamper != null)
  78.                     stamper.Close();
  79.                 if (os != null)
  80.                     os.Close();
  81.             }
  82.         }
  83.  
  84.         static void Main(String[] args) {
  85.             LoggerFactory.GetInstance().SetLogger(new SysoLogger());
  86.  
  87.             // Creates a Cryptoki object related to the specific PKCS#11 native library
  88.             Cryptoki cryptoki = new Cryptoki("beidpkcs11.dll");
  89.             cryptoki.Initialize();
  90.            
  91.  
  92.             // Reads the set of slots containing a token
  93.             SlotList slots = cryptoki.Slots;
  94.             if(slots.Count == 0) {
  95.                Console.WriteLine("No slot available");
  96.                return;
  97.             }
  98.             // Gets the first slot available
  99.             Slot slot = slots[0];
  100.             if(!slot.IsTokenPresent) {
  101.                 Console.WriteLine("No token inserted in the slot: " + slots[0].Info.Description);
  102.                 return;
  103.             }
  104.  
  105.             // Gets the first token available
  106.             Token token = slot.Token;
  107.  
  108.             // Opens a read/write serial session
  109.             Session session =
  110.                 token.OpenSession(Session.CKF_SERIAL_SESSION | Session.CKF_RW_SESSION, null, null);
  111.  
  112.             // Executes the login passing the user PIN
  113.             //int nRes = session.Login(Session.CKU_USER, "0000");
  114.             /*if (nRes != 0) {
  115.                 Console.WriteLine("Wrong PIN");
  116.                 return;
  117.             }*/
  118.  
  119.             Smartcardsign(session, "Authentication");
  120.             Smartcardsign(session, "Signature");
  121.            
  122.             // Logouts and closes the session
  123.             session.Logout();
  124.             session.Close();
  125.             cryptoki.Finalize(IntPtr.Zero);
  126.         }
  127.  
  128.         public static void Smartcardsign(Session session, String alias) {
  129.             // Searchs for an RSA certificate object
  130.             // Sets the template with its attributes
  131.             CryptokiCollection template = new CryptokiCollection();
  132.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_CLASS, CryptokiObject.CKO_CERTIFICATE));
  133.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_CERTIFICATE_TYPE, Certificate.CKC_X_509));
  134.             template.Add(new ObjectAttribute(ObjectAttribute.CKA_LABEL, alias));
  135.  
  136.             Cryptware.NCryptoki.X509Certificate nCert = (Cryptware.NCryptoki.X509Certificate)session.Objects.Find(template);
  137.            
  138.             X509Certificate2 cert = Utils.ConvertCertificate(nCert);
  139.             ICollection chain = new List();
  140.             X509Chain x509chain = new X509Chain();
  141.             x509chain.Build(cert);
  142.  
  143.             foreach (X509ChainElement x509ChainElement in x509chain.ChainElements) {
  144.                 chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
  145.             }
  146.  
  147.             IOcspClient ocspClient = new OcspClientBouncyCastle();
  148.             List crlList = new List();
  149.             crlList.Add(new CrlClientOnline(chain));
  150.             C4_03_SignWithPKCS11SC app = new C4_03_SignWithPKCS11SC();
  151.             app.Sign(SRC, String.Format(DEST, alias), chain, session, alias, DigestAlgorithms.SHA256, CryptoStandard.CMS,
  152.                     "Test", "Ghent", crlList, ocspClient, null, 0);
  153.         }
  154.     }
  155. }
C4_07_ClientServerSigning.cs
  1. /*
  2.  * This class is part of the white paper entitled
  3.  * "Digital Signatures for PDF documents"
  4.  * written by Bruno Lowagie
  5.  *
  6.  * For more info, go to: http://itextpdf.com/learn
  7.  */
  8.  
  9. using System;
  10. using System.Collections.Generic;
  11. using System.IO;
  12. using System.Net;
  13. using Org.BouncyCastle.X509;
  14. using iTextSharp.text;
  15. using iTextSharp.text.pdf;
  16. using iTextSharp.text.pdf.security;
  17.  
  18. namespace signatures.chapter4 {
  19.     class C4_07_ClientServerSigning {
  20.         public const String SRC = "../../../../resources/hello.pdf";
  21.         public const String DEST = "../../../../results/chapter4/hello_server.pdf";
  22.  
  23.         public const String CERT = "http://demo.itextsupport.com/SigningApp/itextpdf.cer";
  24.        
  25.         public class ServerSignature : IExternalSignature {
  26.             public const String SIGN = "http://demo.itextsupport.com/SigningApp/signbytes";
  27.            
  28.             public String GetHashAlgorithm() {
  29.                 return DigestAlgorithms.SHA256;
  30.             }
  31.  
  32.             public String GetEncryptionAlgorithm() {
  33.                 return "RSA";
  34.             }
  35.  
  36.             public byte[] Sign(byte[] message) {
  37.                 MemoryStream baos = new MemoryStream();
  38.                 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(SIGN);
  39.                 request.Method = "POST";
  40.                 Stream ostream = request.GetRequestStream();
  41.                 ostream.Write(message, 0, message.Length);
  42.                 ostream.Close();
  43.                 HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  44.                 Stream istream = response.GetResponseStream();
  45.                 byte[] b = new byte[0x1000];
  46.                 int read;  
  47.                 while ((read = istream.Read(b, 0, b.Length)) != 0)  
  48.                     baos.Write(b, 0, read);
  49.                 istream.Close();
  50.                 return baos.ToArray();
  51.             }
  52.            
  53.         }
  54.        
  55.         public void Sign(String src, String dest, ICollection chain,
  56.                 CryptoStandard subfilter, String reason, String location) {
  57.             // Creating the reader and the stamper
  58.             PdfReader reader = new PdfReader(src);
  59.             FileStream os = new FileStream(dest, FileMode.Create);
  60.             PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '\0');
  61.             // Creating the appearance
  62.             PdfSignatureAppearance appearance = stamper.SignatureAppearance;
  63.             appearance.Reason = reason;
  64.             appearance.Location = location;
  65.             appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, "sig");
  66.             // Creating the signature
  67.             IExternalSignature signature = new ServerSignature();
  68.             MakeSignature.SignDetached(appearance, signature, chain, null, null, null, 0, subfilter);
  69.         }
  70.        
  71.         public static void Main(String[] args) {
  72.             X509CertificateParser parser = new X509CertificateParser();
  73.             Stream url = WebRequest.Create(CERT).GetResponse().GetResponseStream();
  74.             ICollection chain = new List();
  75.             chain.Add(parser.ReadCertificate(url));
  76.             C4_07_ClientServerSigning app = new C4_07_ClientServerSigning();
  77.             app.Sign(SRC, DEST, chain, CryptoStandard.CMS, "Test", "Ghent");
  78.         }
  79.     }
  80. }
C4_08_ServerClientSigning.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.IO;
  11. using System.Net;
  12. using Org.BouncyCastle.Crypto;
  13. using Org.BouncyCastle.Pkcs;
  14. using Org.BouncyCastle.Security;
  15.  
  16. namespace signatures.chapter4 {
  17.     class C4_08_ServerClientSigning {
  18.         public const String CERT = "../../../../resources/bruno.crt";
  19.         public const String KEYSTORE = "../../../../resources/pkcs12";
  20.         public static char[] PASSWORD = "password".ToCharArray();
  21.         public const String DEST = "../../../../results/chapter4/hello_server2.pdf";
  22.  
  23.         public const String PRE = "http://demo.itextsupport.com/SigningApp/presign";
  24.         public const String POST = "http://demo.itextsupport.com/SigningApp/postsign";
  25.        
  26.         public static void Main(String[] args) {
  27.             // we make a connection to a PreSign servlet
  28.             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(PRE);
  29.             request.Method = "POST";
  30.             // we upload our self-signed certificate
  31.             Stream os = request.GetRequestStream();
  32.             FileStream fis = new FileStream(CERT, FileMode.Open);
  33.             int read;
  34.             byte[] data = new byte[0x100];
  35.             while ((read = fis.Read(data, 0, data.Length)) != 0)
  36.                 os.Write(data, 0, read);
  37.             os.Flush();
  38.             os.Close();
  39.            
  40.             HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  41.             // we use cookies to maintain a session
  42.             String cookies = response.Headers["Set-Cookie"];
  43.             // we receive a hash that needs to be signed
  44.             Stream istream = response.GetResponseStream();
  45.             MemoryStream baos = new MemoryStream();
  46.             data = new byte[0x100];
  47.             while ((read = istream.Read(data, 0, data.Length)) != 0)  
  48.                 baos.Write(data, 0, read);  
  49.             istream.Close();
  50.             byte[] hash = baos.ToArray();
  51.            
  52.             // we load our private key from the key store
  53.             Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
  54.             String alias = "";
  55.             // searching for private key
  56.             foreach (string al in store.Aliases)
  57.                 if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
  58.                     alias = al;
  59.                     break;
  60.                 }
  61.             AsymmetricKeyEntry pk = store.GetKey(alias);
  62.  
  63.             // we sign the hash received from the server
  64.             ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");
  65.             sig.Init(true, pk.Key);
  66.             sig.BlockUpdate(hash, 0, hash.Length);
  67.             data = sig.GenerateSignature();
  68.            
  69.             // we make a connection to the PostSign Servlet
  70.             request = (HttpWebRequest)WebRequest.Create(POST);
  71.             request.Headers.Add(HttpRequestHeader.Cookie,cookies.Split(";".ToCharArray(), 2)[0]);
  72.             request.Method = "POST";
  73.             // we upload the signed bytes
  74.             os = request.GetRequestStream();
  75.             os.Write(data, 0, data.Length);
  76.             os.Flush();
  77.             os.Close();
  78.  
  79.             // we receive the signed document
  80.             response = (HttpWebResponse)request.GetResponse();
  81.             istream = response.GetResponseStream();
  82.             FileStream fos = new FileStream(DEST, FileMode.Create);
  83.             data = new byte[0x100];
  84.             while ((read = istream.Read(data, 0, data.Length)) != 0)
  85.                 fos.Write(data, 0, read);
  86.             istream.Close();
  87.             fos.Flush();
  88.             fos.Close();
  89.         }
  90.     }
  91. }
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