You need to enable JavaScript to run this app. 使用PDFBox+HSM签名PDF后提示“文档已被篡改”的问题排查
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFBox+HSM签名PDF后提示“文档已被篡改”的问题排查

PDF签名验证失败问题排查求助

我正在使用HSM服务对PDF进行签名,该服务接收文档哈希并返回签名后的哈希。签名流程如下:

  • 接收Base64格式的PDF,创建PDDocument并添加可视化签名;
  • 使用ExternalSigningSupport对象获取数据哈希并发送至HSM进行签名;
  • 调用sign方法添加证书和签名后的哈希。

接收端获取签名后的PDF时,签名验证不通过,提示**"Document has been altered or corrupted since it was signed"**。我确认签名后未修改文档,仅进行必要的字节处理以返回响应。

核心签名代码

PDDocument doc = PDDocument.load(request.getRequest().getFile());
            
float page_width = doc.getPage(page).getMediaBox().getWidth();
float page_height = doc.getPage(page).getMediaBox().getHeight();

// Calculate position for signature
float sqr_width = page_width / num_cols;
float sqr_height = page_height / num_rows;
float pos_X = page_width - sqr_width - (sqr_width * (num_cols - column));
float pos_Y = page_height - sqr_height - (sqr_height * (num_rows - row));

GetCertificatebyTotpIDOutput certificateBody= getCertificate();     


PDSignature signature = new PDSignature();
signature.setFilter( PDSignature.FILTER_ADOBE_PPKLITE );
signature.setSubFilter( PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setReason( "Test" );
signature.setSignDate(Calendar.getInstance());

Rectangle2D humanRect = new Rectangle2D.Float(); 
humanRect.setFrame(new Point2D.Float(pos_X, pos_Y), new Dimension((int) sqr_width, (int) sqr_height));

PDRectangle rect = createSignatureRectangle(doc, humanRect);

InputStream template = createVisualSignatureTemplate( doc, page, rect, signature, certificateBody ); // Implementation defined below.
SignatureOptions options = new SignatureOptions();
options.setVisualSignature( template );
options.setPage(0);
options.setPreferredSignatureSize(9000);

doc.addSignature( signature, options );


FileOutputStream outputStream = new FileOutputStream(filePath);

ExternalSigningSupport externalSigning = doc.saveIncrementalForExternalSigning(outputStream);

byte[] input = IOUtils.toByteArray(externalSigning.getContent());
byte[] hash = MessageDigest.getInstance("SHA-256").digest(input);
String digest = new String(Base64.getEncoder().encode(hash));

System.out.println("Before signing: " + new String(Base64.getEncoder().encode(hash)));

byte[] signedContent3 = Files.readAllBytes(Paths.get(filePath));
byte[] hash3 = MessageDigest.getInstance("SHA-256").digest(signedContent3);
System.out.println("File OS hash: " + new String(Base64.getEncoder().encode(hash3)));


SigFinalizeOutput signedDoc = signDocument(certificateBody.getCertAlias(), "test_pdf", digest, "test", totpID, totp);
String base64HashSig = signedDoc.getSignedDocsInfo().get(0).getHashSig();

byte[] cmsSignature = sign(externalSigning.getContent(), base64HashSig);

externalSigning.setSignature(cmsSignature);

sign方法代码

public byte[] sign(InputStream content, String signedHash) throws IOException {

    // cannot be done private (interface)
    try {
        GetCertificatebyTotpIDOutput certificateBody= getCertificate(); 
        String base64CertificateString = certificateBody.getCert_64();

//        byte[] certificateBytes = Base64.getDecoder().decode(base64CertificateString);
//        CertificateFactory cf = CertificateFactory.getInstance("X.509");
//        X509Certificate certificate = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(certificateBytes));

        byte[] decoded = Base64.getDecoder().decode(base64CertificateString);
        Collection collection = null;
        try {
            collection = CertificateFactory.getInstance("X.509").generateCertificates(new ByteArrayInputStream(decoded));
        } catch (CertificateException e) {

        }
          
        Certificate[] certChain = new Certificate[collection.size()];
        Iterator iterator = collection.iterator();
        int i = 0;
        while (iterator.hasNext()) {
            certChain[i++] = (Certificate) iterator.next();
        }
        
        // Certificate chain is acquired at initialization
        List<Certificate> certList = new ArrayList<>();
        for (Certificate cert : certChain) {
            certList.add(cert);
        }
        Store certStore= new JcaCertStore(certList);
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate.getInstance(certChain[0].getEncoded());
        
        X509Certificate signerCert = (X509Certificate) certChain[0];
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        gen.addCertificates(certStore);
      
        byte[] input = IOUtils.toByteArray(content);


        MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        messageDigest.update(input);
        System.out.println("During signing: " + new String(Base64.getEncoder().encode(messageDigest.digest())));
        Attribute attr = new Attribute(CMSAttributes.messageDigest, new DERSet(new DEROctetString(messageDigest.digest())));
        ASN1EncodableVector v = new ASN1EncodableVector();
        v.add(attr);

        ContentSigner contentSigner = new ContentSigner() {
            
            @Override
            public byte[] getSignature() {
                 System.out.println(String.valueOf(Base64.getDecoder().decode(signedHash)));
                return Base64.getDecoder().decode(signedHash);
            }

            @Override
            public OutputStream getOutputStream() {
                return new ByteArrayOutputStream() ;
            }

            @Override
            public AlgorithmIdentifier getAlgorithmIdentifier() {
                return new DefaultSignatureAlgorithmIdentifierFinder().find("SHA256WITHDSA");
            }
        };

        SignerInfoGeneratorBuilder builder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider())
                .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(new AttributeTable(v)));
        gen.addSignerInfoGenerator(builder.build(contentSigner, new X509CertificateHolder(cert)));
        //gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(contentSigner, signerCert));
        
        
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        
        CMSSignedData cmsSignedData = gen.generate(msg, true);
        byte[] result =cmsSignedData.getEncoded();

        return result;

    } catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
        throw new IOException(e);
    }
}

我曾尝试计算byte range,但发现externalSigning.getContent()已返回不含签名对象的PDF数据,以下是具体排查方向建议:

排查方向

  • 修复InputStream重复读取问题:
    externalSigning.getContent()返回的InputStream只能读取一次,核心代码中先调用IOUtils.toByteArray(externalSigning.getContent())读取内容,之后再把externalSigning.getContent()传给sign方法时,流已经被耗尽,导致sign方法中读取的内容为空,计算的哈希错误。建议将第一次读取的byte[]转换成ByteArrayInputStream传给sign方法:
    // 替换原代码中调用sign的部分
    byte[] cmsSignature = sign(new ByteArrayInputStream(input), base64HashSig);
    
  • 验证哈希一致性:
    确保发送给HSM的哈希(digest变量)和sign方法中计算的哈希完全一致。可以在sign方法中直接使用传入的文档byte[]计算哈希,避免重复读取流导致的不一致。
  • 匹配签名算法:
    检查HSM实际使用的签名算法是否与代码中指定的SHA256WITHDSA一致。如果HSM使用RSA算法,需将AlgorithmIdentifier改为SHA256WITHRSA,算法不匹配会直接导致签名验证失败。
  • 检查CMS签名结构:
    使用BouncyCastle的CMS解析工具查看生成的CMS签名,确认Signed Attributes中的messageDigest属性值与文档哈希一致,同时验证证书链是否完整包含所有必要的中间证书和根证书。
  • 确认签名大小足够:
    检查options.setPreferredSignatureSize(9000)设置的大小是否能容纳生成的CMS签名。如果签名实际大小超过该值,会导致PDF文件被截断或损坏,触发验证错误。

内容的提问来源于stack exchange,提问作者dmb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 18:35:08