I want to digitally sign a PDF file using a certificate stored on a USB-token, HSM, etc. How do I use the private key stored on the USB token using JAVA?
To the iText self-reference, I'll add
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" minus c from above
(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 Temporary 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.
Seems like you want to digitally sign a PDF using an USB token, a smart-card or a Hardware Security Module. This is done through PKCS#11 as explained in http://itextpdf.com/book/digitalsignatures You can find the source code here. This is an example showing how to sign using a SafeNet iKey 400 USB token.