使用iTextSharp向PDF添加数字签名

Adding a Digital signature to a PDF with iTextSharp(使用iTextSharp向PDF添加数字签名)
本文介绍了使用iTextSharp向PDF添加数字签名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

我使用iTextSharp已经有一段时间了。我已经创建了一个具有两个可签名的PdfFormFields的pdf文档。如果我打开pdf文档,我可以手动在每个字段上手动签名。我希望这是通过iTextSharp完成的。

我当前正在从X509Store检索证书。到目前为止,我还能搞清楚。

问题

谁能告诉我如何使用这个X509证书2 若要对已有的签名Acrofield签名,请执行以下操作。

参考资料

访问了以下参考资料,但我找不到我想要的答案。 Signing a pdf document

我相信这个链接是最接近的,但使用的几行代码是无效的,我不知道是否可以通过包含一些其他库来修复它。 https://www.dotnetportal.cz/blogy/15/Null-Reference-Exception/5250/Digitalni-podepisovani-PDF-souboru-v-C-cast-2

推荐答案

您需要的一切:

appearance.SetVisibleSignature("---> ExistSignatureName <-----");
MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);

完整代码:

private static void SignPdf(string filename, string folderPdf, string pathToNewSignFile, string pathToCerts, string nameCert, string passCert)
{      
    var pathToCert = GetFullNameFile(pathToCerts, nameCert); //Oh.. I did not know about the Path.Combine function.

    if (!File.Exists(pathToCert))
    {
        logger.Error("Certificate not exist " + pathToCert);
        return;
    }

    var pass = passCert.ToCharArray();

    FileStream fs;
    try
    {
        fs = new FileStream(pathToCert, FileMode.Open);
    }
    catch (Exception ex)
    {
        logger.Error(ex, "Could not open cert" + pathToCert);
        return;
    }

    var store = new Pkcs12Store(fs, pass);

    fs.Close();

    var alias = "";

    // searching for private key
    foreach (string al in store.Aliases)
        if (store.IsKeyEntry(al) && store.GetKey(al).Key.IsPrivate) {
            alias = al;
            break;
        }

    var pk = store.GetKey(alias);

    ICollection<X509Certificate> chain = store.GetCertificateChain(alias).Select(c => c.Certificate).ToList();

    var parameters = pk.Key as RsaPrivateCrtKeyParameters;

    var pathPdf = GetFullNameFile(folderPdf, filename); //Oh.. I did not know about the Path.Combine function.

    var pathToSigPdf = GetFullNameFile(pathToNewSignFile, filename);

    if (!File.Exists(pathPdf))
    {
        logger.Error("Could not open file" + pathPdf + "  File not exist");
        return;
    }

    var reader = new PdfReader(pathPdf);


    FileStream fileStreamSigPdf;
    try
    {
        fileStreamSigPdf = new FileStream(pathToSigPdf, FileMode.Create);
    }
    catch (Exception ex)
    {
        logger.Error(ex, "Could not create file" + pathToSigPdf);
        return;
    }

    var stamper = PdfStamper.CreateSignature(reader, fileStreamSigPdf, '', null, true);

    var appearance = stamper.SignatureAppearance;
    appearance.Reason = "Утверждено";

    appearance.SetVisibleSignature("---> ExistSignatureName <-----");

    IExternalSignature pks = new PrivateKeySignature(parameters, DigestAlgorithms.SHA256);
    MakeSignature.SignDetached(appearance, pks, chain, null, null, null, 0, CryptoStandard.CMS);

    fileStreamSigPdf.Close();
    reader.Close();
    stamper.Close();

    logger.Info("Signed successfully " + filename);
}

我们公司有一台Web服务器。 1.获取哈希字段 2.在密码插件的帮助下,我们对哈希进行了签名 3.在字段中插入签名

步骤1。

public string PrepareSignatureAndGetHash()
    {
        var hash = string.Empty;

        using (var reader = new PdfReader("PathTemplate"))
        {
            using (var fileStream = File.OpenWrite("PathToTemp"))
            {
                using (var stamper = PdfStamper.CreateSignature(reader, fileStream, '0', null, true))
                {
                    var signatureAppearance = stamper.SignatureAppearance;
                    signatureAppearance.SetVisibleSignature("ExistSignatureName");
                    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                    signatureAppearance.Reason = "Sig";
                    signatureAppearance.Layer2Text = "Super SIG";

                    signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;

                    MakeSignature.SignExternalContainer(signatureAppearance, external, 8192);


                    using (var contentStream = signatureAppearance.GetRangeStream())
                    {
                        hash = string.Join(string.Empty, SHA1.Create().ComputeHash(contentStream).Select(x => x.ToString("X2")));
                    }
                }
            }
        }

    return hash;
}

第2步。

public void SigSignature(string base64String)
{
    using (var reader = new PdfReader("PathToTemp"))
    {
        using (var fileStream = File.OpenWrite("PathToSig"))
        {
            var byteSig = Convert.FromBase64String(base64String);
            IExternalSignatureContainer external = new MfuaExternalSignatureContainer(byteSig);

            MakeSignature.SignDeferred(reader, "ExistSignatureName", fileStream, external);
        }
    }
}

private class MfuaExternalSignatureContainer : IExternalSignatureContainer
{
    private readonly byte[] _signedBytes;

    public MfuaExternalSignatureContainer(byte[] signedBytes)
    {
        _signedBytes = signedBytes;
    }

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

    public void ModifySigningDictionary(PdfDictionary signDic)
    {
    }
}

这篇关于使用iTextSharp向PDF添加数字签名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)