Sign a Pdf using custom digital signature in Java

2019-06-05 07:04发布

问题:

I've created a digital signature using Sun's code:http://download.oracle.com/javase/tutorial/security/apisign/examples/GenSig.java. How can I sign a pdf file using this digital signature? That is: how can I add the signature to a pdf file?

回答1:

You've taken the wrong approach. You can't easily append the signature to the PDF. PDF specification includes support for digital signatures. Those signatures are embedded into the document, and their calculation is a non-trivial process.

Your best bet is to drop your current implementation and take eg. iText library or our SecureBlackbox which will do the job for you.

If your task is to implement signature yourself, then take PDF specification, read it and implement the corresponding pieces of it (and in this case your question is way too broad to be answered in StackOverflow format).



回答2:

Steps involved in Adding Digital Signature to a PDF File:

(I) Create Template PDFDocument :

Create PDFDocument with template signature:
PDSignature pdSignature,
pdSignature.setByteRange(new int[]{0, 0, 0, 0});
pdSignature.setContents(new byte[n*1024]);

where n is an integer, ie multiple of kbs.

Note: Content Size should be greater than or equal to sum of length of Signature and Certificate File.

(II) Update the Template PDF Docuement :

(a) Update /ByteRange[a b c d]:
(i) a= Offset of % in "%PDF"(=0, by default)
(ii) b= Offset of < in "/Contents<000...000>"
(iii) c= Offset of > in "/Contents<000...000>"
(iv) d= Offset of F in "%%EOF"-c

(b) update xref section:
update the cross-reference table(xref section), that specifies the position of the objects and

(c) Update startxref section:
update startxref, which is the offset of start of cross-reference table(xref).

(III) Generate Digital Signature of the Updated Template Document:
Generate of the Updated Template Document Excluding the Signed Data ("000...000) of "/Contents<000...000>"

(IV) Update Content<> Section:
Substitute First/Initial "0"s of Signed Data length in "/Contents<000...000>" with Signed Data (Enveloped) of template PDFFile.

Suggestions:

Use SignatureInterface of PDFBox :

(a) implement SignatureInterface to call sign() method (b) supply the input, output files, keystore, alias, pin (c) do save incrment

(or) use any java pdf library (like iText...)

(or) Implement the Steps I-IV in java yourself.