iTextSharp - 如何获取用于签名的 PDF 内容,然后稍后再签名

iTextSharp - How to get PDF content for signing and then sign at a later time

我正在开发一个客户端-服务器应用程序,客户端必须使用他们的签名签署 PDF 文档并将它们上传到服务器。由于客户无法将签名嵌入 PDF,他们只能读取原始字节并以原始字节的形式生成签名,因此任务变得复杂。

我正在尝试实施以下工作流程:

  1. 客户端上传未签名的PDF到服务器
  2. 服务器打开 PDF,提取客户端需要签名的字节,并将这些字节发回
  3. 客户端接收这些字节,使用客户端证书对它们进行签名并将签名发送到服务器
  4. 服务器将收到的签名嵌入到它之前收到的 PDF 中。

我找到了一些提取字节进行签名并将签名字节嵌入到 PDF 中的代码示例 (this is the main sample I'm using)。

问题在于此示例在一个程序中执行所有步骤,它在获取文档哈希后立即嵌入签名而不关闭 PdfStamper。我需要的是在添加签名字段并获得 sha.Hash 之后保存文档的某种方法,然后在稍后的某个时间(当服务器收到计算出的签名时)打开文档并将签名值嵌入到 PDF 中。

您能否建议一种修改此代码的方法,以便步骤 (2) 和 (4) 可以独立,并且不需要 PdfReaderPdfStamper 的共享实例?

以下答案来自我们的 white paper on digital signatures, chapter 4, section 4.3.3 Signing a document on the server using a signature created on the client. Code examples here

所需的工作流程可分为 3 个主要步骤:

  1. 预签名:
    要求:pdf、证书链
    服务器端,设置签名基础设施,提取消息摘要并将摘要作为字节数组

  2. 发送给客户端
  3. 签约:
    必需:消息摘要作为字节数组,私钥
    客户端,将加密算法应用于消息摘要以从哈希生成签名摘要并将此签名发送到 服务器

  4. 后缀: 必需:签名摘要作为字节数组,pdf 服务器端 将已签名的摘要插入准备好的签名中,插入 在 pdf 文档中签名

代码示例,iText5 和 C#:

预签名(服务器)

//hello : 
//location of the pdf on the server
//or
//bytestream variable with teh pdf loaded in
//chain: certificate chain
// we create a reader and a stamper
PdfReader reader = new PdfReader(hello);
Stream baos = new MemoryStream();
PdfStamper stamper = PdfStamper.CreateSignature(reader,  baos., '[=10=]');
// we create the signature appearance
PdfSignatureAppearance sap = stamper.SignatureAppearance;
sap.Reason = "Test";
sap.Location = "On a server!";
sap.SetVisibleSignature ( new Rectangle(36, 748, 144, 780), 1, "sig");
sap.Certificate = chain[0];
// we create the signature infrastructure
PdfSignature dic = new PdfSignature(
PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
dic.Reason = sap.Reason;
dic.Location = sap.Location;
dic.Contact = sap.Contact;
dic.Date = new PdfDate(sap.SignDate);
sap.CryptoDictionary = dic;
Dictionary<PdfName, int> exc = new Dictionary<PdfName, int>();
exc.Add(PdfName.CONTENTS, (int)(8192 * 2 + 2));
sap.PreClose(exc);
PdfPKCS7 sgn = new PdfPKCS7(null, chain, "SHA256", false);
//Extract the bytes that need to be signed
Stream data = sap.GetRangeStream();
byte[] hash = DigestAlgorithms.Digest(data,"SHA256");
byte[] sh = sgn.getAuthenticatedAttributeBytes(hash,null, null, CryptoStandard.CMS);
//Store sgn, hash,sap and baos on the server
//...
//Send sh to client

签名(客户)

// we receive a hash that needs to be signed
Stream istream = response.GetResponseStream();
MemoryStream baos = new MemoryStream();
data = new byte[0x100];
while ((read = istream.Read(data, 0, data.Length)) != 0)  
    baos.Write(data, 0, read);  
istream.Close();
byte[] hash = baos.ToArray();

// we load our private key from the key store
Pkcs12Store store = new Pkcs12Store(new FileStream(KEYSTORE, FileMode.Open), PASSWORD);
String alias = "";
// searching for private key
foreach (string al in store.Aliases)
    if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
        alias = al;
        break;
    }
AsymmetricKeyEntry pk = store.GetKey(alias);

// we sign the hash received from the server
ISigner sig = SignerUtilities.GetSigner("SHA256withRSA");
sig.Init(true, pk.Key);
sig.BlockUpdate(hash, 0, hash.Length);
data = sig.GenerateSignature();

// we make a connection to the PostSign Servlet
request = (HttpWebRequest)WebRequest.Create(POST);
request.Headers.Add(HttpRequestHeader.Cookie,cookies.Split(";".ToCharArray(), 2)[0]);
request.Method = "POST";
// we upload the signed bytes
os = request.GetRequestStream();
os.Write(data, 0, data.Length);
os.Flush();
os.Close();

Postsign(服务器)

// we read the signed bytes
MemoryStream baos = new MemoryStream();
Stream InputStream iStream = req.GetInputStream();
int read;
byte[] data = new byte[256];
while ((read = iStream.read(data, 0, data.Length)) != -1) {
    baos.Write(data, 0, read);
}
// we complete the PDF signing process
sgn.SetExternalDigest(baos.ToArray(), null, "RSA");
byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null,
null, null, CryptoStandard.CMS);
byte[] paddedSig = new byte[8192];
paddedSig.
encodedSig.CopyTo(paddedSig, 0);
PdfDictionary dic2 = new PdfDictionary();
dic2.Put(PdfName.CONTENTS, new PdfString(paddedSig).SetHexWriting(true));
try
{
    sap.close(dic2);
}
catch (DocumentException e)
{
    throw new IOException(e);
}

我省略了大部分客户端-服务器通信代码,并专注于签名逻辑。我也没有彻底测试这些片段,因为我必须从 java 代码转换它们,而且我目前没有客户端-服务器设置来测试它们,所以复制并 运行 在你的风险自负。

我自己想出来了。 This piece of code 给我指出了正确的方向。

原来服务器上的进程必须如下:

  • 获取未签名的 PDF 并添加一个空的签名字段
  • 根据文件修改后的内容计算需要签名的字节数
  • 将修改后的带有空签名的 PDF 保存到临时文件中
  • 将计算后的字节发送给客户端
  • 当客户端响应签名时,打开临时文件并将签名插入到之前创建的字段中

相关服务器代码:

public static byte[] GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
{
    using (PdfReader reader = new PdfReader(unsignedPdf))
    {
        using (FileStream os = File.OpenWrite(tempPdf))
        {
            PdfStamper stamper = PdfStamper.CreateSignature(reader, os, '[=10=]');
            PdfSignatureAppearance appearance = stamper.SignatureAppearance;
            appearance.SetVisibleSignature(new Rectangle(36, 748, 144, 780), 1, signatureFieldName);
            IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
            MakeSignature.SignExternalContainer(appearance, external, 8192);

            return SHA1Managed.Create().ComputeHash(appearance.GetRangeStream());
        }
    }
}
public static void EmbedSignature(string tempPdf, string signedPdf, string signatureFieldName, byte[] signedBytes)
{
    using (PdfReader reader = new PdfReader(tempPdf))
    {
        using (FileStream os = File.OpenWrite(signedPdf))
        {
            IExternalSignatureContainer external = new MyExternalSignatureContainer(signedBytes);
            MakeSignature.SignDeferred(reader, signatureFieldName, os, external);
        }
    }
}

private class MyExternalSignatureContainer : IExternalSignatureContainer
{
    private readonly byte[] signedBytes;

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

    public byte[] Sign(Stream data)
    {
        return signedBytes;
    }

    public void ModifySigningDictionary(PdfDictionary signDic)
    {
    }
}

旁注:在所有这些 iText 示例中困扰我的是幻数的存在(如此处的 8192),但没有任何评论。这使得使用这个库比它本来应该的更加困难和烦人。