【问题标题】:iText7 deferred signed pdf document shows “the document has been altered or corrupted since the signature was applied”iText7 延迟签名的 pdf 文档显示“自应用签名以来文档已被更改或损坏”
【发布时间】:2021-05-11 22:36:53
【问题描述】:

我在 Stackoverflow 上检查了其他类似问题,但它不适用于我的情况。

情况:我正在开发一个需要签署 pdf 文档的应用程序。签名密钥由另一家公司持有,假设是 CompanyA。

我做了以下步骤:

  1. 准备好要签署的 pdf 文档。
  2. 创建了一个临时 pdf 文件,在原始 pdf 中添加了一个空签名。
  3. 阅读 Temp pdf 以获取消息摘要。 (将其编码为 base64)
  4. 将消息摘要(Base64 编码)发送到 CompanyA 以进行签名。
  5. 从 CompanyA 获取签名摘要(base64 编码)。
  6. 进行 base64 解码。并将结果嵌入到 Temp pdf 中以获得最终签名的 pdf。

一切顺利,我可以得到最终签名的 pdf。但是当我在 Adob​​e 阅读器中打开它时,它会显示“自从应用签名后,该文档已被更改或损坏”。

我使用这个getHashBase64Str2Sign 来获取消息摘要(在base64 中)。该方法调用emptySignature()方法创建空签名的Temp文件,然后调用getSignatureHash()方法读取Temp文件获取消息摘要。

public static String getHashBase64Str2Sign() {
    try {
        // Add BC provider
        BouncyCastleProvider providerBC = new BouncyCastleProvider();
        Security.addProvider(providerBC);

        // Create parent path of dest pdf file, if not exist
        File file = new File(DEST).getParentFile();
        if (!file.exists()) {
            file.mkdirs();
        }


        CertificateFactory factory = CertificateFactory.getInstance("X.509");
        Certificate[] chain = new Certificate[1];
        try (InputStream certIs = new FileInputStream(CERT)) {
            chain[0] = factory.generateCertificate(certIs);
        }

        // Get byte[] hash
        DeferredSigning app = new DeferredSigning();

        app.emptySignature(SRC, TEMP, "sig", chain);

        byte[] sh = app.getSignatureHash(TEMP, "SHA256", chain);

        // Encode byte[] hash to base64 String and return
        return Base64.getEncoder().encodeToString(sh);
    } catch (IOException | GeneralSecurityException e) {
        e.printStackTrace();
        return null;
    }
}

    

private void emptySignature(String src, String dest, String fieldname, Certificate[] chain)
        throws IOException, GeneralSecurityException {
    PdfReader reader = new PdfReader(src);
    PdfSigner signer = new PdfSigner(reader, new FileOutputStream(dest), new StampingProperties());
    PdfSignatureAppearance appearance = signer.getSignatureAppearance();
    appearance.setPageRect(new Rectangle(100, 500, 200, 100));
    appearance.setPageNumber(1);
    appearance.setCertificate(chain[0]);
    appearance.setReason("For test");
    appearance.setLocation("HKSAR");
    signer.setFieldName(fieldname);

    /*
     * ExternalBlankSignatureContainer constructor will create the PdfDictionary for
     * the signature information and will insert the /Filter and /SubFilter values
     * into this dictionary. It will leave just a blank placeholder for the
     * signature that is to be inserted later.
     */
    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite,
            PdfName.Adbe_pkcs7_detached);
    

    // Sign the document using an external container.
    // 8192 is the size of the empty signature placeholder.
    signer.signExternalContainer(external, 100000);
}

private byte[] getSignatureHash(String src, String hashAlgorithm, Certificate[] chain)
        throws IOException, GeneralSecurityException {
    InputStream is = new FileInputStream(src);
    // Get the hash
    BouncyCastleDigest digest = new BouncyCastleDigest();
    PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);

    byte hash[] = DigestAlgorithms.digest(is, digest.getMessageDigest(sgn.getHashAlgorithm()));
    return sgn.getAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS, null, null);
}

private void createSignature(String src, String dest, String fieldName, byte[] sig)
        throws IOException, GeneralSecurityException {
    PdfReader reader = new PdfReader(src);
    try (FileOutputStream os = new FileOutputStream(dest)) {
        PdfSigner signer = new PdfSigner(reader, os, new StampingProperties());

        IExternalSignatureContainer external = new MyExternalSignatureContainer(sig);

        // Signs a PDF where space was already reserved. The field must cover the whole
        // document.
        PdfSigner.signDeferred(signer.getDocument(), fieldName, os, external);
    }
}

然后,消息摘要被发送到 CompanyA 进行签名。从 CompanyA 获得签名摘要(base64 编码)后,我调用 embedSignedHashToPdf() 方法获取签名的 pdf 文档。

public static void embedSignedHashToPdf(String signedHash) {
    try {
        byte[] sig = Base64.getDecoder().decode(signedHash);
        // Get byte[] hash
        DeferredSigning app = new DeferredSigning();
        app.createSignature(TEMP, DEST, "sig", sig);
    } catch (IOException | GeneralSecurityException e) {
        e.printStackTrace();
    }
}

class MyExternalSignatureContainer implements IExternalSignatureContainer {

    protected byte[] sig;

    public MyExternalSignatureContainer(byte[] sig) {
        this.sig = sig;
    }

    @Override
    public void modifySigningDictionary(PdfDictionary signDic) {

    }

    @Override
    public byte[] sign(InputStream arg0) throws GeneralSecurityException {
        return sig;
    }

}

我终于可以得到签名的pdf文档了,但是在Adobe Reader中显示错误,像这样:

请检查原始pdf、临时pdf和最终签名的pdf文件如下:

Original pdf - helloworld.pdf

Temp pdf - helloworld_empty_signed.pdf

Final pdf - helloworld_signed_ok.pdf

【问题讨论】:

    标签: pdf itext digital-signature deferred corrupt


    【解决方案1】:

    好的,我在您的代码中发现了一些问题:

    你确定了错误字节的哈希

    getSignatureHashsrc 中包含准备签署的中间PDF 的路径

    InputStream is = new FileInputStream(src);
    ...
    byte hash[] = DigestAlgorithms.digest(is, ...);
    

    即您计算整个中间 PDF 的哈希值。

    这是不正确的!

    必须为 PDF 计算哈希值,但稍后嵌入的签名容器的占位符除外:

    散列该范围的最简单方法是已经计算 emptySignature 中的散列,并使用计算散列的 IExternalSignatureContainer 实现而不是愚蠢的 ExternalBlankSignatureContainer 从那里返回它。

    例如使用这个实现:

    public class PreSignatureContainer implements IExternalSignatureContainer {
        private PdfDictionary sigDic;
        private byte hash[];
    
        public PreSignatureContainer(PdfName filter, PdfName subFilter) {
            sigDic = new PdfDictionary();
            sigDic.put(PdfName.Filter, filter);
            sigDic.put(PdfName.SubFilter, subFilter);
        }
    
        @Override
        public byte[] sign(InputStream data) throws GeneralSecurityException {
            String hashAlgorithm = "SHA256";
            BouncyCastleDigest digest = new BouncyCastleDigest();
    
            try {
                this.hash = DigestAlgorithms.digest(data, digest.getMessageDigest(hashAlgorithm));
            } catch (IOException e) {
                throw new GeneralSecurityException("PreSignatureContainer signing exception", e);
            }
    
            return new byte[0];
        }
    
        @Override
        public void modifySigningDictionary(PdfDictionary signDic) {
            signDic.putAll(sigDic);
        }
    
        public byte[] getHash() {
            return hash;
        }
    }
    

    像这样:

    PreSignatureContainer external = new PreSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
    signer.signExternalContainer(external, 16000);
    byte[] documentHash = external.getHash();
    

    您处理哈希的方式就像您的 CompanyA 只返回裸签名字节,但您嵌入 CompanyA 返回的字节,就好像它们是完整的 CMS 签名容器一样

    getSignatureHash 中,您最终不会返回所谓的文档哈希,而是开始构建 CMS 签名容器并返回其签名属性:

    PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);
    ...
    return sgn.getAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS, null, null);
    

    只有当您随后检索这些属性字节的裸签名字节并使用相同的 PdfPKCS7 对象创建 CMS 签名容器时,计算 PdfPKCS7.getAuthenticatedAttributeBytes(...) 才有意义:

    byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, sigtype, ocspList, crlBytes);
    byte[] extSignature = RETRIEVE_NAKED_SIGNATURE_BYTES_FOR(sh);
    sgn.setExternalDigest(extSignature, null, ENCRYPTION_ALGORITHM_USED_FOR_SIGNING);
    
    byte[] encodedSig = sgn.getEncodedPKCS7(hash, sigtype, tsaClient, ocspList, crlBytes);
    

    尤其是您计算签名属性然后忘记PdfPKCS7 对象的方法根本没有任何意义。

    但实际上,您的 CompanyA 似乎可以返回完整的 CMS 签名容器,而不仅仅是裸签名字节,因为您立即将返回的字节嵌入到 embedSignedHashToPdfcreateSignature 中,并且您的示例 PDF 确实包含完整的 CMS 签名容器。

    在这种情况下,您根本不需要使用PdfPKCS7,而是直接将预先计算好的文档摘要发送给CompanyA进行签名。

    因此,您很可能根本不需要PdfPKCS7,而是将如上所述确定的文档哈希发送到 CompanyA 并嵌入他们返回的签名容器。

    【讨论】:

    • 谢谢mkl!你是救生员!我将代码从 ExternalBlankSignatureContainer 更改为 PreSignatureContainer 并且它有效。没错,CompanyA 返回完整的 CMS 签名容器。在这种情况下不需要PdfPKCS7。再次感谢!
    猜你喜欢
    • 2023-04-03
    • 2021-11-06
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 2016-09-16
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多