使用PDFBox 2.0.29添加CMS签名后PDF签名损坏的问题求助
PDFBox 2.0.29添加CMS签名后PDF签名损坏的问题求助
大家好,我最近在做PDF签名功能时遇到了个麻烦,想请各位帮忙看看。
我尝试用PdfBox 2.0.29版本结合CMS签名给PDF文档签名,但每次生成的PDF里签名都是损坏的,打开后会提示“document has been altered or corrupted since it was signed”。我希望能把签名成功添加到PDF中,并且让签名处于有效状态,不知道有没有办法解决这个问题?
以下是我目前使用的代码:
public ResponseEntity<String> signPdf(@RequestParam String pdfPath, @RequestParam String cmsSignature64){ try{ // Decode CMS signature from Base64 byte[] cmsSignature = java.util.Base64.getDecoder().decode(cmsSignature64); // Load the PDF document Path pdfFilePath = Path.of(pdfPath); if(!Files.exists(pdfFilePath)){ return ResponseEntity.badRequest().body("PDF file not found at:" + pdfPath); } File inputFile = pdfFilePath.toFile(); PDDocument document = PDDocument.load(inputFile); // Create a new signature PDSignature signature = new PDSignature(); signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE); signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED); signature.setReason("QualifiedCertification"); signature.setLocation(""); signature.setSignDate(Calendar.getInstance()); signature.setContents(new byte[8192]); // Add the signature field with a specific name signature.setName("DetachedSignature"); document.addSignature(signature); // Prepare the external signature ExternalSigningSupport externalSigning = document.saveIncrementalForExternalSigning(new FileOutputStream(inputFile)); // Write the detached CMS signature to the PDF externalSigning.setSignature(cmsSignature); // Save and close the document document.close(); return ResponseEntity.ok("PDF signed successfully:" + pdfFilePath.toString()); }catch(Exception e){ e.printStackTrace(); return ResponseEntity.status(500).body("Error while signing PDF:" + e.getMessage()); } }
备注:内容来源于stack exchange,提问作者Rui Silva
相关产品推荐
相关产品推荐

