PDF在C#中使用iTextSharp使用USB令牌签名

时间:2017-04-22 05:12:11

标签: asp.net itext digital-signature

我正在尝试使用C#中的iTextSharp使用USB令牌签署PDF文件,并且没有取得任何成功。如果有人有任何解决方案从USB令牌获取证书并在C#中使用数字签名的PDF文件。

1 个答案:

答案 0 :(得分:3)

以下是获取证书的代码:

X509CertificateParser cp = new X509CertificateParser();

        //Get Sertifiacte
        X509Certificate2 certClient = null;
        X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
        st.Open(OpenFlags.MaxAllowed);
        X509Certificate2Collection collection = X509Certificate2UI.SelectFromCollection(st.Certificates,
            "Please choose certificate:", "", X509SelectionFlag.SingleSelection);
        if (collection.Count > 0)
        {
            certClient = collection[0];
        }
        st.Close();
        //Get Cert Chain
        IList<X509Certificate> chain = new List<X509Certificate>();
        X509Chain x509Chain = new X509Chain();

        x509Chain.Build(certClient);

        foreach (X509ChainElement x509ChainElement in x509Chain.ChainElements)
        {
            chain.Add(DotNetUtilities.FromX509Certificate(x509ChainElement.Certificate));
        }

这是我的签名代码:

PdfReader inputPdf = new PdfReader(fileInsert);

                FileStream signedPdf = new FileStream(File_rename(fileInsert, "_signed"), FileMode.Create);

                PdfStamper pdfStamper = PdfStamper.CreateSignature(inputPdf, signedPdf, '\0');

                IExternalSignature externalSignature = new X509Certificate2Signature(certClient, "SHA-1");

                PdfSignatureAppearance signatureAppearance = pdfStamper.SignatureAppearance;

                //signatureAppearance.SignatureGraphic = Image.GetInstance(pathToSignatureImage);
                //signatureAppearance.SetVisibleSignature(new iTextSharp.text.Rectangle(0, 00, 250, 150), inputPdf.NumberOfPages, "Signature");
                signatureAppearance.SignatureRenderingMode = PdfSignatureAppearance.RenderingMode.DESCRIPTION;

                MakeSignature.SignDetached(signatureAppearance, externalSignature, chain, null, null, null, 0,
                    CryptoStandard.CMS);
                inputPdf.Close();
                pdfStamper.Close();

fileinsert是您要签名的文件名

File_rename(fileInsert, "_signed")

是一种重命名原始文件名的方法,如&#34; noname.pdf&#34; to&#34; noname_signed.pdf&#34;。

使用的库:

using Org.BouncyCastle.Security;
using Org.BouncyCastle.X509;
using System.Security.Cryptography.X509Certificates;
using X509Certificate = Org.BouncyCastle.X509.X509Certificate;

我希望它有所帮助,我几年前使用我找到的搜索论坛的一些例子编写了代码,但我有时仍会使用它。