Skip to content

Instantly share code, notes, and snippets.

@alexbartlow
Created October 15, 2014 18:16

Revisions

  1. alexbartlow created this gist Oct 15, 2014.
    33 changes: 33 additions & 0 deletions gistfile1.java
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,33 @@
    The signing implementation
    The SignImp class isnt much different from all the examples weve written before. When I write
    Servlets that involve the use of iText, I always start by writing a short standalone application with a
    main() method. This way I can test the code before integrating it into a web application.
    In code sample 4.11, Ive removed the main() method for brevity.
    Code sample 4.11: the SignImp class
    public class SignImp {
    private PrivateKey pk;
    private Certificate[] chain;
    public SignImp(PrivateKey pk, Certificate[] chain) {
    this.pk = pk;
    this.chain = chain;
    }
    public byte[] signDoc(InputStream pdf, String reason, String location)
    throws GeneralSecurityException, IOException, DocumentException {
    // Creating the reader and the stamper
    PdfReader reader = new PdfReader(pdf, null);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PdfStamper stamper =
    PdfStamper.createSignature(reader, baos, '\0', null, true);
    // Creating the appearance
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setReason(reason);
    appearance.setLocation(location);
    // Creating the signature
    ExternalSignature pks =
    new PrivateKeySignature(pk, DigestAlgorithms.SHA256, null);
    ExternalDigest digest = new BouncyCastleDigest();
    MakeSignature.signDetached(appearance, digest, pks, chain,
    null, null, null, 0, CryptoStandard.CMS);
    return baos.toByteArray();
    }
    }