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

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

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

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

  • 准备文档(PdfReader)
  • 将文档的哈希值返回给用户
  • 扔掉文档(PdfReader)
  • 让用户进行身份验证(与 iText 签名过程没有直接关系)并创建签名 (PKCS1)
  • 如果用户已通过身份验证,请重新准备文档并应用签名。

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

我的问题是创建的哈希值总是不同的。 (即使我通过 pdfSigner.SetSignDate 将日期/时间设置为相同的值)或每个 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));

问题:有没有办法

  • 在 PdfReader 的一个实例上“提前”生成 pdf 文档的哈希
  • 创建签名
  • 在 PdfReader 的不同实例上应用签名

附上一个完整的流程示例(包括签名创建,实际上需要由不同的服务完成)

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));

                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,PdfSigner.CryptoStandard.CMS);
            //Create the signature via own certificate
            signature = CreateSignature(sh,Program.privateKeyFile,Program.privateKeyPassword);
            pkcs7Signature.SetExternalDigest(signature,"RSA");
            return pkcs7Signature.GetEncodedPKCS7(hash,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


    }
}

解决方法

问题:有没有办法

  • 在 PdfReader 的一个实例上“提前”生成 pdf 文档的哈希
  • 创建签名
  • 在 PdfReader 的不同实例上应用签名

iText 目前不支持此用例,特别是在每次传递中

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res