Example usage for org.apache.pdfbox.pdmodel.interactive.digitalsignature SignatureInterface sign

List of usage examples for org.apache.pdfbox.pdmodel.interactive.digitalsignature SignatureInterface sign

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.interactive.digitalsignature SignatureInterface sign.

Prototype

byte[] sign(InputStream content) throws IOException;

Source Link

Document

Creates a cms signature for the given content

Usage

From source file:com.aaasec.sigserv.csspsupport.pdfbox.modifications.CsCOSWriter.java

License:Apache License

private void doWriteSignature(COSDocument doc) throws IOException, SignatureException {
    // need to calculate the ByteRange
    if (signaturePosition[0] > 0 && byterangePosition[1] > 0) {
        int left = (int) getStandardOutput().getPos() - signaturePosition[1];
        String newByteRange = "0 " + signaturePosition[0] + " " + signaturePosition[1] + " " + left + "]";
        int leftByterange = byterangePosition[1] - byterangePosition[0] - newByteRange.length();
        if (leftByterange < 0) {
            throw new IOException("Can't write new ByteRange, not enough space");
        }/* ww  w.j  a va 2  s  .c o  m*/
        getStandardOutput().setPos(byterangePosition[0]);
        getStandardOutput().write(newByteRange.getBytes());
        for (int i = 0; i < leftByterange; ++i) {
            getStandardOutput().write(0x20);
        }

        getStandardOutput().setPos(0);
        // Begin - extracting document
        InputStream filterInputStream = new COSFilterInputStream(in,
                new int[] { 0, signaturePosition[0], signaturePosition[1], left });
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[1024];
            int c;
            while ((c = filterInputStream.read(buffer)) != -1) {
                bytes.write(buffer, 0, c);
            }
        } finally {
            if (filterInputStream != null) {
                filterInputStream.close();
            }
        }

        byte[] pdfContent = bytes.toByteArray();
        // End - extracting document

        SignatureInterface signatureInterface = doc.getSignatureInterface();
        byte[] sign = signatureInterface.sign(new ByteArrayInputStream(pdfContent));
        String signature = new COSString(sign).getHexString();
        int leftSignaturerange = signaturePosition[1] - signaturePosition[0] - signature.length();
        if (leftSignaturerange < 0) {
            throw new IOException("Can't write signature, not enough space");
        }
        getStandardOutput().setPos(signaturePosition[0] + 1);
        getStandardOutput().write(signature.getBytes());
    }
}