Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
829 views
in Technique[技术] by (71.8m points)

certificate - How to sign pdf in Java using pdfbox

I am trying to sign pdf using pdfbox libraries. I have stuck now and realy need a help.

This is my code:

private static void signPdf(PDDocument document) throws Exception 
{
    PDSignature sig = new PDSignature();
    sig.setFilter(COSName.ADOBE_PPKLITE);
    sig.setSubFilter(COSName.ADBE_PKCS7_DETACHED);
    sig.setByteRange(new int[] {'a','a','a','a'});
    sig.setContents(new byte[]{(byte) 23, (byte) 23, (byte) 23, (byte) 23});

    SignatureOptions options = new SignatureOptions();

    document.addSignature(sig, new SignatureInterface() {
        public byte[] sign(InputStream content)
                throws SignatureException, IOException       {        
             //this should be made MD5 checksum?           
            return new byte[]{(byte) 'a', (byte) 'a', (byte) 'a', (byte) 'a'};
        }
    }, options);
}

Then Iam saving my pdf, but: 1) I have noticed that sign method is never called 2) Where should I attach certyficate? in sign method?

pdf:

/Type /Sig
/Filter /Adobe.PPKLite
/SubFilter /adbe.pkcs7.sha1
/Contents <0000000000. a lot of zeros..000>
/ByteRange [0 1000000000 1000000000 1000000000]

I think that i miss something, but documentation says nothing about how to sign a file.

Tahnks in advance JC.

@Ed

Here is how I save my pdf:

public static void saveFile(COSDocument doc, String out)
        throws IOException, COSVisitorException {  
    java.io.OutputStream os = null;  
    COSWriter writer = null;  
    try {
        os = new java.io.FileOutputStream(out);
        writer = new COSWriter(os);
        writer.write(doc);
    } finally {
        if (os != null) {
            os.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The linked PDFBox-SignExample.zip is out of date. Please use this sample instead:

https://svn.apache.org/repos/asf/pdfbox/trunk/examples/src/main/java/org/apache/pdfbox/examples/signature/CreateSignature.java

It is better documented and kept up-to-date.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...