如何使用 iText IExternalSignatureContainer 提前创建 pdf 哈希

Howto create the pdf hash ahead of time using iText IExternalSignatureContainer

我正在使用 iText 7 将签名应用于 pdf 文档。我还使用自己的 IExternalSignatureContainer 实现,以便将证书集成到 PKCS7 CMS 中,因为签名服务仅 returns PKCS1 签名。

签名过程是异步的(用户必须进行身份验证)我想执行以下操作:

原因是我没有将准备好的文档保存在内存中,也没有用于批量签名。

我的问题是创建的散列值总是不同的。 (即使我通过 pdfSigner.SetSignDate 将 date/time 设置为相同的值)或每个 PdfReader/PdfSigner 实例。

            //Create the hash of of the pdf document 
            //Part of my IExternalSignatureContainer Sign method
            //Called from iText pdfSigner.SignExternalContainer
            //The produced hash is always different
            byte[] hash = DigestAlgorithms.Digest(pdfStream, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

问题:有没有办法

附件是该过程的完整示例(包括实际需要由不同服务完成的签名创建)

using System;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using iText.Kernel.Pdf;
using iText.Signatures;
using Org.BouncyCastle.X509;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;

namespace SignExternalTestManuel
{
    class Program
    {
        const string filePath = @"c:\temp\pdfsign\";
        public static string pdfToSign = Path.Combine(filePath, @"test.pdf");
        public static string destinationFile = Path.Combine(filePath, "test_signed.pdf");
        public static string LocalUserCertificatePublicKey = Path.Combine(filePath, "BITSignTestManuel5Base64.cer");
        public static string LocalCaCertificatePublicKey = Path.Combine(filePath, "BITRoot5Base64.cer");
        public static string privateKeyFile = Path.Combine(filePath, "BITSignTestManuel5.pfx");
        public static string privateKeyPassword = "test";

        public static void Main(String[] args)
        {
            PdfReader reader = new PdfReader(pdfToSign);
            using (FileStream os = new FileStream(destinationFile, FileMode.OpenOrCreate))
            {
                
                StampingProperties stampingProperties = new StampingProperties();
                stampingProperties.UseAppendMode();
                PdfSigner pdfSigner = new PdfSigner(reader, os, stampingProperties);
                pdfSigner.SetCertificationLevel(PdfSigner.NOT_CERTIFIED);

                IExternalSignatureContainer external = new GsSignatureContainer(
                    PdfName.Adobe_PPKLite,
                    PdfName.Adbe_pkcs7_detached);

                pdfSigner.SetSignDate(new DateTime(2021, 2, 22, 10, 0, 0));

                pdfSigner.SetFieldName("MySignatureField");
                pdfSigner.SignExternalContainer(external, 32000);
            }
        }
    }


    public class GsSignatureContainer : IExternalSignatureContainer
    {
        private PdfDictionary sigDic;


        public GsSignatureContainer(PdfName filter, PdfName subFilter)
        {
            sigDic = new PdfDictionary();
            sigDic.Put(PdfName.Filter, filter);
            sigDic.Put(PdfName.SubFilter, subFilter);
        }

        /// <summary>
        /// Implementation based on https://kb.itextpdf.com/home/it7kb/examples/how-to-use-a-digital-signing-service-dss-such-as-globalsign-with-itext-7#HowtouseaDigitalSigningService(DSS)suchasGlobalSign,withiText7-Examplecode
        /// </summary>
        /// <param name="pdfStream"></param>
        /// <returns></returns>
        public byte[] Sign(Stream pdfStream)
        {
            //Create the certificate chaing since the signature is just a PKCS1, the certificates must be added to the signature
            X509Certificate[] chain = null;


            string cert = System.IO.File.ReadAllText(Program.LocalUserCertificatePublicKey);
            string ca = System.IO.File.ReadAllText(Program.LocalCaCertificatePublicKey);
            chain = CreateChain(cert, ca);

            X509CrlParser p = new X509CrlParser();

            String hashAlgorithm = DigestAlgorithms.SHA256;
            PdfPKCS7 pkcs7Signature = new PdfPKCS7(null, chain, hashAlgorithm, false);

            //Create the hash of of the pdf document 
            //Part of my IExternalSignatureContainer Sign method
            //Called from iText pdfSigner.SignExternalContainer
            //The produced hash is always different
            byte[] hash = DigestAlgorithms.Digest(pdfStream, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

            byte[] signature = null;

            //Create the hash based on the document hash which is suitable for pdf siging with SHA256 and a X509Certificate
            byte[] sh = pkcs7Signature.GetAuthenticatedAttributeBytes(hash, null, null, PdfSigner.CryptoStandard.CMS);
            //Create the signature via own certificate
            signature = CreateSignature(sh, Program.privateKeyFile, Program.privateKeyPassword);
            pkcs7Signature.SetExternalDigest(signature, null, "RSA");
            return pkcs7Signature.GetEncodedPKCS7(hash, null, null, null, PdfSigner.CryptoStandard.CMS);
        }

        public void ModifySigningDictionary(PdfDictionary signDic)
        {
            signDic.PutAll(sigDic);
        }

        private static X509Certificate[] CreateChain(String cert, String ca)
        {
            //Note: The root certificate could be omitted and it would still work
            X509Certificate[] chainy = new X509Certificate[2];
            X509CertificateParser parser = new X509CertificateParser();
            chainy[0] = new X509Certificate(parser.ReadCertificate(Encoding.UTF8.GetBytes(cert))
                .CertificateStructure);
            chainy[1] = new X509Certificate(parser.ReadCertificate(Encoding.UTF8.GetBytes(ca))
                .CertificateStructure);
            return chainy;
        }

        #region "Create signature, will be done by an actual service"
        private byte[] CreateSignature(byte[] hash, string privateKeyFile, string privateKeyPassword)
        {
            //Sign data directly with a X509Certificate
            X509Certificate2 rootCertificateWithPrivateKey = new X509Certificate2();
            byte[] rawData = System.IO.File.ReadAllBytes(privateKeyFile);
            rootCertificateWithPrivateKey.Import(rawData, privateKeyPassword, X509KeyStorageFlags.Exportable);

            using (var key = rootCertificateWithPrivateKey.GetRSAPrivateKey())
            {
                return key.SignData(hash, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            }
        }
        #endregion


    }
}

Question: Is there a way to

  • Produce the hash of a pdf document "ahead of time" on one instance of the PdfReader
  • Create the signature
  • Apply the signature on a different instance of the PdfReader

iText 当前不支持此用例,尤其是在每个传递中

  • 生成了一个不同的 PDF ID,
  • 使用不同的修改时间,并且
  • 对于 AES 加密的 PDF,用于加密的随机数不同。

可以对 iText 进行修补以在每次传递中使用相同的值,但在对库进行修补之前,您应该考虑是否可以调整您的体系结构以使修补程序变得不必要。

例如,在您的情况下,如果您无法保留原始 PdfSigner 实例,另一种方法可能是在散列后让原始 PdfSigner 存储其结果文件和虚拟签名字节 (例如 new byte[0])。然后,在检索签名容器后,您可以使用 PdfSigner.signDeferred 将其注入到不同服务中的存储文件中,只要两个服务都可以访问共享存储(或者第一个服务至少可以将文件转发到第二个服务)。