如何在 Web 应用程序中使用 USB 令牌对 PDF 进行签名?

How to Sign PDF using USB Token in Web Application?

我想在用户使用 asp.net Web 应用程序中客户端计算机中的 USB 令牌上传文件时签署 PDF。

我正在关注之前的 SO Post Sign PDF with iTextSharp 5.3.3 and USB token

它运行良好,当我将它发布到 Web 服务器时在本地执行时它给出异常当前会话不是交互式的。

堆栈跟踪:

[InvalidOperationException: The current session is not interactive.]

System.Security.Cryptography.CAPI.CryptUIDlgSelectCertificateW(CRYPTUI_SELECTCERTIFICATE_STRUCTW csc) +345679
System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromStore(SafeCertStoreHandle safeSourceStoreHandle, String title, String message, X509SelectionFlag selectionFlags, IntPtr hwndParent) +314
System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollectionHelper(X509Certificate2Collection certificates, String title, String message, X509SelectionFlag selectionFlag, IntPtr hwndParent) +176
System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollection(X509Certificate2Collection certificates, String title, String message, X509SelectionFlag selectionFlag) +17 test.WebForm1.Upload_Click(Object sender, EventArgs e) in E:\manishtest\test\test\WebForm1.aspx.cs:74
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +138
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +150 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +6047

我是第一次对 PDF 进行数字签名。请建议在上传时在网络应用程序中签署 PDF 的方式。

似乎是这一行引起了问题:

System.Security.Cryptography.X509Certificates.X509Certificate2UI.SelectFromCollectionHelper(X509Certificate2Collection certificates, String title, String message, X509SelectionFlag selectionFlag, IntPtr hwndParent)

shows UI到select一个证书。所以你需要找到另一种方法来获得证书才能让它发挥作用。

您可以尝试the code in an answer您引用的问题使用证书文件而不是文件来选择证书。

X509Certificate2 cert = new X509Certificate2("C:\mycert.p12");

编辑:正如 @Bruno Lowagie 评论的那样,通过 U 盘签名意味着它是由 U 盘上的软件完成的,而不是将私钥发送到任何地方。他的第二条评论更详细地说明了如何实现这一点。但是得到那个错误仍然是一样的。服务器上的代码 运行 无法打开对话框以在客户端系统上选择证书。