使用C#中的iTextSharp在PDF中添加多个数字签名

时间:2017-01-19 06:12:51

标签: itext digital-signature

我使用iTextSharp Dll实现了数字签名,只需一个签名即可对PDF文件进行签名。现在,我想在之前或已经过数字签名的PDF中添加另一个数字签名,并且在验证一个签名时出现错误。

如何在一个PDF中添加多个数字签名并验证所有签名。

我正在使用以下代码:

PdfReader reader = new PdfReader(fileName);
using (FileStream fout = new FileStream(SignedFileName, FileMode.Create, FileAccess.ReadWrite))
{
    // appearance
    PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');
    PdfSignatureAppearance appearance = stamper.SignatureAppearance;
    //appearance.Reason = SignReason;
    //appearance.Location = SignLocation;
    appearance.SignDate = DateTime.Now.Date;
    appearance.SetVisibleSignature(new iTextSharp.text.Rectangle(xPos, yPos, xPos + 200, yPos + 100), PageNo, null);//.IsInvisible

    // Custom text and background image
    appearance.Image = iTextSharp.text.Image.GetInstance(SignatureImg);
    appearance.ImageScale = 0.6f;
    appearance.Image.Alignment = 300;
    appearance.Acro6Layers = true;

    StringBuilder buf = new StringBuilder();
    buf.Append("Digitally Signed by ");
    String name = SignerName;

    buf.Append(name).Append('\n');
    buf.Append("Date: ").Append(DateTime.Now.ToString("dd-MM-yyyy HH:mm:ss zzz"));

    string text = buf.ToString();

    appearance.Layer2Text = text;

    //digital signature
    IExternalSignature es = new PrivateKeySignature(pk, "SHA-256");
    MakeSignature.SignDetached(appearance, es, new Org.BouncyCastle.X509.X509Certificate[] { pk12.GetCertificate(alias).Certificate }, null, null, null, 0, CryptoStandard.CMS);

    stamper.Close();

}

1 个答案:

答案 0 :(得分:2)

错误在这一行:

global_var = 2

var foo = function(){
  console.log("y", this.global_var)
}

var bar = (function b(){
  var global_var = 300;

  var x = function(){
    console.log("x", this.global_var);
  };

  var y = foo;

  return {x: x, y: y, global_var: global_var};
})();

foo();                       // 2

bar.x();                     // 300
bar.y();                     // 300

setTimeout(bar.x);           // 2
setTimeout(bar.y);           // 2

setTimeout(bar.x.bind(bar)); // 300
setTimeout(bar.y.bind(bar)); // 300

将其更改为:

PdfStamper stamper = PdfStamper.CreateSignature(reader, fout, '\0');

说明:您没有以追加模式签署文件。

在进一步检查代码时,我发现您还要添加图片。这可能很棘手。在追加模式中添加新签名解决了一个问题。添加额外内容可能会导致额外问题,具体取决于您使用的iText版本。