Certificate encryption

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

31st May 2016
iText PDF

Switch code for this example

EncryptWithCertificate.java
  1. /*
  2.  
  3.     This file is part of the iText (R) project.
  4.     Copyright (c) 1998-2016 iText Group NV
  5.  
  6. */
  7.  
  8. /**
  9.  * This example was written by Bruno Lowagie.
  10.  */
  11. package com.itextpdf.samples.sandbox.security;
  12.  
  13. import com.itextpdf.kernel.pdf.EncryptionConstants;
  14. import com.itextpdf.kernel.pdf.PdfDocument;
  15. import com.itextpdf.kernel.pdf.PdfReader;
  16. import com.itextpdf.kernel.pdf.PdfWriter;
  17. import com.itextpdf.kernel.pdf.WriterProperties;
  18. import com.itextpdf.kernel.utils.CompareTool;
  19. import com.itextpdf.layout.Document;
  20. import com.itextpdf.layout.element.Paragraph;
  21. import com.itextpdf.samples.GenericTest;
  22. import com.itextpdf.test.ITextTest;
  23. import com.itextpdf.test.annotations.type.SampleTest;
  24.  
  25. import org.bouncycastle.jce.provider.BouncyCastleProvider;
  26. import org.junit.experimental.categories.Category;
  27.  
  28. import java.io.File;
  29. import java.io.FileInputStream;
  30. import java.io.IOException;
  31. import java.security.KeyStore;
  32. import java.security.KeyStoreException;
  33. import java.security.NoSuchAlgorithmException;
  34. import java.security.PrivateKey;
  35. import java.security.Security;
  36. import java.security.UnrecoverableKeyException;
  37. import java.security.cert.Certificate;
  38. import java.security.cert.CertificateException;
  39. import java.security.cert.CertificateFactory;
  40. import java.security.cert.X509Certificate;
  41.  
  42. import static org.junit.Assert.assertNull;
  43.  
  44. /**
  45.  * The file created using this example can not be opened, unless
  46.  * you import the private key stored in test.p12 in your certificate store.
  47.  * The password for the p12 file is kspass.
  48.  *
  49.  *
  50.  * Due to import control restrictions by the governments of a few countries,
  51.  * the encryption libraries shipped by default with the Java SDK restrict the
  52.  * length, and as a result the strength, of encryption keys. Be aware that in
  53.  * this sample by using {@link ITextTest#removeCryptographyRestrictions()} we
  54.  * remove cryptography restrictions via reflection for testing purposes.
  55.  *
  56.  * For more conventional way of solving this problem you need to replace the
  57.  * default security JARs in your Java installation with the Java Cryptography
  58.  * Extension (JCE) Unlimited Strength Jurisdiction Policy Files. These JARs
  59.  * are available for download from http://java.oracle.com/ in eligible countries.
  60.  */
  61. @Category(SampleTest.class)
  62. public class EncryptWithCertificate extends GenericTest {
  63.     public static final String DEST
  64.             = "./target/test/resources/sandbox/security/encrypt_with_certificate.pdf";
  65.     public static final String SRC
  66.             = "./src/test/resources/pdfs/hello_encrypted.pdf";
  67.     public static final String PUBLIC
  68.             = "./src/test/resources/encryption/test.cer";
  69.     public static final String PRIVATE
  70.             = "./src/test/resources/encryption/test.p12";
  71.  
  72.     public static void main(String[] args) throws Exception {
  73.         File file = new File(DEST);
  74.         file.getParentFile().mkdirs();
  75.         new EncryptWithCertificate().manipulatePdf(DEST);
  76.     }
  77.  
  78.     public Certificate getPublicCertificate(String path) throws IOException, CertificateException {
  79.         FileInputStream is = new FileInputStream(path);
  80.         CertificateFactory cf = CertificateFactory.getInstance("X.509");
  81.         X509Certificate cert = (X509Certificate) cf.generateCertificate(is);
  82.         return cert;
  83.     }
  84.  
  85.     @Override
  86.     protected void manipulatePdf(String dest) throws Exception {
  87.         Security.addProvider(new BouncyCastleProvider());
  88.  
  89.         Certificate cert = getPublicCertificate(PUBLIC);
  90.         PdfWriter writer = new PdfWriter(DEST, new WriterProperties()
  91.                 .setPublicKeyEncryption(
  92.                         new Certificate[]{cert},
  93.                         new int[]{EncryptionConstants.ALLOW_PRINTING},
  94.                         EncryptionConstants.ENCRYPTION_AES_256));
  95.  
  96.  
  97.         PdfDocument pdfDoc = new PdfDocument(writer);
  98.         Document doc = new Document(pdfDoc);
  99.         doc.add(new Paragraph("My secret hello"));
  100.         doc.close();
  101.     }
  102.  
  103.     @Override
  104.     protected void beforeManipulatePdf() {
  105.         super.beforeManipulatePdf();
  106.         ITextTest.removeCryptographyRestrictions();
  107.     }
  108.  
  109.     @Override
  110.     protected void afterManipulatePdf() {
  111.         super.afterManipulatePdf();
  112.         ITextTest.restoreCryptographyRestrictions();
  113.     }
  114.  
  115.     @Override
  116.     protected void comparePdf(String dest, String cmp) throws Exception {
  117.         if (cmp == null || cmp.length() == 0) return;
  118.         CompareTool compareTool = new CompareTool();
  119.         PrivateKey privateKey = getPrivateKey();
  120.         compareTool.getOutReaderProperties().setPublicKeySecurityParams(getPublicCertificate(PUBLIC), privateKey, "BC", null);
  121.         compareTool.getCmpReaderProperties().setPublicKeySecurityParams(getPublicCertificate(PUBLIC), privateKey, "BC", null);
  122.         compareTool.enableEncryptionCompare();
  123.         String outPath = new File(dest).getParent();
  124.         new File(outPath).mkdirs();
  125.         if (compareXml) {
  126.             if (!compareTool.compareXmls(dest, cmp)) {
  127.                 addError("The XML structures are different.");
  128.             }
  129.         } else {
  130.             if (compareRenders) {
  131.                 addError(compareTool.compareVisually(dest, cmp, outPath, differenceImagePrefix));
  132.                 addError(compareTool.compareLinkAnnotations(dest, cmp));
  133.             } else {
  134.                 addError(compareTool.compareByContent(dest, cmp, outPath, differenceImagePrefix));
  135.             }
  136.             addError(compareTool.compareDocumentInfo(dest, cmp));
  137.         }
  138.  
  139.         assertNull(errorMessage);
  140.     }
  141.  
  142.     private PrivateKey getPrivateKey() throws KeyStoreException, IOException, UnrecoverableKeyException, NoSuchAlgorithmException, CertificateException {
  143.         KeyStore keystore = KeyStore.getInstance("PKCS12");
  144.         keystore.load(new FileInputStream(PRIVATE), "kspass".toCharArray());
  145.         return (PrivateKey) keystore.getKey("sandbox", "kspass".toCharArray());
  146.     }
  147. }
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