gpt4 book ai didi

asp.net - 在 C# 中使用 iTextSharp 使用 USB token 进行 PDF 签名

转载 作者:行者123 更新时间:2023-12-02 10:46:02 28 4
gpt4 key购买 nike

我尝试在 C# 中使用 iTextSharp 使用 USB token 对 PDF 文件进行签名,但没有取得任何成功。如果有人有任何解决方案,可以从 USB token 和 C# 中的数字签名 PDF 文件中获取证书。

最佳答案

以下是获取证书的代码:

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

是将原始文件名(如“noname.pdf”)重命名为“noname_signed.pdf”的方法。

以及使用的库:

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

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

关于asp.net - 在 C# 中使用 iTextSharp 使用 USB token 进行 PDF 签名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43555512/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com