我一直在阅读官方的PDFBox示例以对PDF文档进行可视化签名,特别是CreateVisualSignature2.java中的示例,该示例生成一个空文档作为模板来定义签名外观,然后通过调用SignatureOptions将其设置为真实文档.setVisibleSignature()。
就我而言,我一直在使用HSM服务为我签名,因此我无法直接访问私钥或证书。我将文档哈希发送到此服务,它返回一个PKCS7字节数组,该数组是使用ExternalSigningSupport.setSignature()添加到我的文档中的。
该代码基于上面链接的PDFBox示例,看起来像这样:
// Read the document and prepare a signature. PDDocument document = PDDocument.load( "path/to/file.pdf" ); PDSignature signature = new PDSignature(); signature.setFilter( PDSignature.FILTER_ADOBE_PPKLITE ); signature.setSubFilter( PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED ); signature.setReason( "Test" ); InputStream template = createVisualSignatureTemplate( document ); // Implementation defined below. SignatureOptions options = new SignatureOptions(); options.setVisibleSignature( template ); options.setPage( 0 ); document.addSignature( signature, options ); // Get the content to sign using PDFBox external signing support. FileOutputStream outputStream = new FileOutputStream(); ExternalSigningSupport externalSigning = document.saveIncrementalForExternalSigning( outputStream ); byte[] content = IOUtils.toByteArray( externalSigning.getContent() ); // Send the content to the HSM service and get the response. byte[] hash = MessageDigest.getInstance( "SHA-256" ).digest( content ); byte[] pkcs7 = MyHSMService.getSignedHash( hash ); // Add the signature to the PDF. externalSigning.setSignature( pkcs7 ); document.close();
还有我的模板方法,基于链接的PDFBox示例中的同名方法,简化了:
PDDocument emptyDocument = new PDDocument(); emptyDocument.addPage( new PDFPage( document.getPage(0).getMediaBox() ) ); // Create the PDAcroForm, PDSignatureField, PDAppearanceDictionary, etc, // just like in the official example. (...) // Define the content stream of the visual signature. PDPageContentStream content = new PDPageContentStream( emptyDocument, appearanceStream ); content.beginText(); content.showText( "Signed by: ... " ); // The signer name should be here. content.newLine(); content.showText( "Date: ..." ); // The signature datetime should be here. content.endText(); content.close(); // Convert the empty document as an input stream and return it, just like the example. (...)
这很好,我可以毫无问题地添加有效的视觉签名。我的问题是我需要在签名外观中添加签名者名称和签名日期,但是由于我在调用HSM服务进行签名之前创建了模板,因此我还无法访问该数据,这就是为什么我需要在文档签名后定义内容。
有没有办法实现这一目标?我是PDF签名的新手,所以我对基本原理的理解很差。
提前感谢!
我一直在阅读官方的PDFBox示例以对PDF文档进行可视化签名,特别是CreateVisualSignature2.java中的示例,该示例生成一个空文档作为模板来定义...
pdf签名的文档内可视化是pdf小部件注释,因此,它是签名内容的一部分。因此,必须在签名之前添加它,并且只能使用签名之前已知的信息。